json数据转换成表格_电子表格会让您失望吗? 将行数据转换为JSON树很容易。

json数据转换成表格

Like many of you, I often have to take the result of SQL queries and convert the rowsets to JSON data objects. Sometimes I have to do the same with CSV files from spreadsheets. The transformation process can be a hassle, though anyone can do it. Yet, it can be time-consuming and error-prone. This post will show you how to use the treeize Node.js package to simplify the process in very few lines of code.

像你们中的许多人一样,我经常不得不获取SQL查询的结果并将行集转换为JSON数据对象 。 有时,我必须对电子表格中的CSV文件执行相同的操作。 转换过程可能很麻烦,尽管任何人都可以做到。 但是,这可能既耗时又容易出错。 这篇文章将向您展示如何使用treeize Node.js包仅需几行代码即可简化该过程。

Before going further, I’ll first need a dataset to base some examples on. The domain will be Books, which lend themselves to all sorts of categorization. I will use a fake data generator called casual, which I previously used for mocks in my post on GraphQL testing.

在继续之前,我首先需要一个数据集以一些示例为基础。 领域将是Books ,这使它们可以进行各种分类。 我将使用一个称为Casual的伪造数据生成器,我先前在GraphQL测试中的帖子中使用过该模型 。

The book data will be of the following structure:

图书数据将具有以下结构:

casual.define('book', () => {const author = casual.random_element(authors);const book = {first_name: author.first,last_name: author.last,title: casual.random_element(author.titles),category: casual.random_element(author.category)}return book;
});

Every time I request a casual.book I get a book with a new set of values. It’s not entirely random. The generator uses some predefined data for well-known authors, and more-or-less randomly generated data for other authors. Here’s a sample:

每次我请求casual.book我都会得到一本casual.book新值的书。 这不是完全随机的。 生成器为知名作者使用一些预定义的数据 ,为其他作者使用或多或少随机生成的数据。 这是一个示例:

{ dataset:[ { first_name: 'Barbara',last_name: 'Cartland',title: 'The Pirate and the Piano Teacher',category: 'thriller' },{ first_name: 'Carlie',last_name: 'Haley',title: 'Digitized Global Orchestration',category: 'engineering' },{ first_name: 'Arthur',last_name: 'Doyle',title: 'The Case of the Spotted Dick',category: 'mystery' },{ first_name: 'Reinhold',last_name: 'Gutmann',title: 'Managed Directional Benchmark',category: 'management' },{ first_name: 'Isaac',last_name: 'Asimov',title: 'Once in a Venusian Sun',category: 'science fiction' },{ first_name: 'R. L.',last_name: 'Stein',title: 'Why are You Scared of Me?',category: 'childrens books' },{ first_name: 'Alicia',last_name: 'Cruickshank',title: 'Balanced Local Database',category: 'engineering' },{ first_name: 'Chase',last_name: 'Runte',title: 'Ergonomic Tertiary Solution',category: 'engineering' } ] }

If you’re interested in how this data was generated, the full source code used in this post can be found here. For a little bit of added realism, this generated data will be thrown into an in-memory SQL database for later retrieval. Here’s the format of the results for the SQL query:

如果您对如何生成这些数据感兴趣,可以在此处找到本文中使用的完整源代码。 为了增加一点真实感,此生成的数据将被扔到内存中SQL数据库中,以便以后进行检索。 这是SQL查询结果的格式:

SELECT title, category, first_name, last_name
FROM book
JOIN author ON author.id = book.author

This format is, for all intents and purposes, identical to the format of the dataset shown just previously, for example:

出于所有目的和目的,此格式与之前显示的数据集的格式相同,例如:

[ { title: 'Proactive Regional Forecast',category: 'mystery',first_name: 'Arthur',last_name: 'Doyle' },{ title: 'More Scary Stuff',category: 'suspense',first_name: 'Steven',last_name: 'King' },{ title: 'Scary Stuff',category: 'occult',first_name: 'Steven',last_name: 'King' },{ title: 'Persistent Neutral Info Mediaries',category: 'management',first_name: 'Maegan',last_name: 'Frami' },{ title: 'Enhanced Background Frame',category: 'engineering',first_name: 'Winifred',last_name: 'Turner' },...

The main difference between the dataset and the rowset is that when populating the database from the casual-generated data, I eliminated duplicate authors (by name) and book titles (by category):

数据集和行集之间的主要区别在于,从临时生成的数据填充数据库时,我消除了重复的作者(按名称)和书名(按类别):

转换为JSON (Converting to JSON)

You might notice that the dataset results were in JSON format already. What this post aims for, though, is to build a containment hierarchy that shows the relationships between authors, books, and categories in a concise way. That’s not the case with the rowset values, where the results are glorified key-value pairs, where each pair is a column name and value from a table row.

您可能会注意到数据集结果已经是JSON格式。 但是,这篇文章的目的是建立一个包含层次结构,以简洁的方式显示作者,书籍和类别之间的关系。 行集值不是这种情况,其中的结果是美化的键值对,其中每个对都是列名和表行中的值。

So, for example, say I want to list authors, the categories they write in, and the titles of books in those categories that they authored. I want to show each category just once, and each book within each category should be listed only once, also.

因此,例如,说我想列出作者,他们所写的类别以及他们所创作的那些类别中的书名。 我只想显示每个类别一次,并且每个类别中的每一本书也应该只列出一次。

This is a pretty common type of reducing operation that is often applied to rowset data. One way to conquer the problem is to declare a container object, then populate it by looping through the rowsets. A typical implementation might be:

这是一种非常常见的归约操作类型,通常应用于行集数据。 解决问题的一种方法是声明一个容器对象,然后通过遍历行集来填充它。 典型的实现可能是:

The handrolled()method gets a bit hairy the deeper the hierarchy. Local variables are used to reduce long path lengths. We have to keep the meta-structure in mind to write the proper initializations of properties in the JSON object. What could be simpler?

handrolled()方法在层次结构越深时变​​得有些毛茸茸。 局部变量用于减少长路径长度。 我们必须牢记元结构,以便在JSON对象中编写属性的正确初始化。 有什么可能更简单?

The results returned are:

返回的结果是:

..."Doyle,Arthur": {"categories": {"thriller": {"titles": ["The Case of the Spotted Dick","The Case of the Mashed Potato"]},"mystery": {"titles": ["The Case of the Spotted Dick"]}}},"Asimov,Isaac": {"categories": {"science": {"titles": ["Once in a Venusian Sun","Total Multi Tasking Forecast"]},"general interest": {"titles": ["Total Multi Tasking Forecast","Once in a Venusian Sun","Fourth Foundation"]}}},"Kilback,Bradley": {"categories": {"management": {"titles": ["Mandatory Solution Oriented Leverage"]},"engineering": {"titles": ["Multi Layered Fresh Thinking Framework","Total Scalable Neural Net","Mandatory Solution Oriented Leverage"]},"reference": {"titles": ["Multi Layered Fresh Thinking Framework"]}}},...

用Treeize构建一棵树 (Building a tree with Treeize)

The npm module treeize is designed to simplify the conversion of rowsets to structured JSON data through the use of descriptive keys. Installation through npm is per usual:

npm模块树化 旨在通过使用描述性键简化行集到结构化JSON数据的转换。 通常通过npm安装:

npm install --save treeize

JSON行集 (JSON Rowsets)

Treeize is able to recognize reoccurring patterns in the rowsets. It transforms them according to how the key names are defined in metadata passed in as the seed structure. Here’s the code:

Treeize能够识别行集中的重复模式。 它根据如何在作为种子结构传入的元数据中定义关键字名称来对其进行转换。 这是代码:

This is about a dozen lines of code compared to double that for the hand-rolled version. Notice the key values used in the mapping operation. Treeize recognizes plurals as collections, so categoriesand titleswill be arrays. The colons (‘:’) in the names indicate nesting. Typewill be a property of an object in the array of categories, and namewill be a property in all objects in titles.

与手动版本相比,这大约是十几行代码。 请注意映射操作中使用的键值。 Treeize将复数形式识别为集合,因此categoriestitles将是数组。 名称中的冒号(':')表示嵌套。 Type将是类别数组中对象的属性, name将是标题中所有对象的属性。

The tree is built when authors.grow(seed) is called, and the results retrieved through authors.getData(). However, it doesn’t quite yield the same results as what we had from the hand-rolled method:

该树是在调用authors.grow(seed)并通过authors.getData()检索结果时构建的。 然而,它并不完全产生相同的结果,我们从手卷方法有:

...,
{"name": "Glover, Ashley","categories": [{"type": "engineering","titles": [{"name": "Intuitive Full Range Capacity"},{"name": "Organic Encompassing Core"}]},{"type": "reference","titles": [{"name": "Distributed Client Server Service Desk"},{"name": "Organic Encompassing Core"}]},{"type": "management","titles": [{"name": "Organic Encompassing Core"}]}]
},...

One notable difference is that categories are not named objects (as before), but objects with a name property. Title is also not just an array of strings, but an array of objects with nameas the title. Treeize interprets categories and titles as arrays of objects, not as maps (or arrays of primitives). For most use cases, this is not much of an issue. But, if you need to find a category by name quickly (rather than iterate through an array of categories), then you can take care of that through a couple of reduce operations to arrive at the same structure as before:

一个显着的区别是类别不是像以前一样命名的对象,而是具有name属性的对象。 Title不仅是一个字符串数组,而且是一个以name为标题的对象数组。 Treeize将categoriestitles解释为对象数组,而不是地图(或基元数组)。 对于大多数用例来说,这不是什么大问题。 但是,如果您需要按名称快速查找类别(而不是遍历一系列类别),则可以通过几次归约操作来达到与以前相同的结构:

,...   "Doyle, Arthur": {"categories": {"mystery": {"titles": ["The Case of the Spotted Dick","Pre Emptive Needs Based Approach","The Case of the Mashed Potato"]},"thriller": {"titles": ["The Case of the Mashed Potato","The Pound Puppies of the Baskervilles"]}}},...

试算表 (Spreadsheets)

Sometimes data comes from spreadsheets rather than relational databases. Treeize is adept at handling this case, too. Instead of using descriptive keys as we did with rowset data in JSON format, the same descriptive format is used as column values in a header row:

有时数据来自电子表格,而不是关系数据库。 Treeize也擅长处理这种情况。 与使用JSON格式的行集数据一样,不使用描述性键,而是将相同的描述性格式用作标题行中的列值:

var seed = [
['name', 'categories:type', 'categories:titles:name'], 
['Doyle, Arthur', 'mystery', 'The Adventure of the Gyring Gerbils'],
['Schuppe, Katarina', 'engineering', 'Configurable Discrete Locks'],
['Doyle, Arthur', 'mystery', 'Holmes Alone 2'],
['Asimov, Isaac', 'science fiction', 'A Crack in the Foundation']
];// same as before...
var authors = new Treeize();
authors.grow(seed);
return authors.getData();

There are quite a few options that treeize supports, and I’ve only shown the basics. It is a powerful tool that makes light work of transforming row-based data structures.

treeize支持的选项有很多,而我仅展示了基础知识。 它是一个强大的工具,可以轻松地转换基于行的数据结构。

Complete source can be found at my GitHub.

完整的源代码可以在我的GitHub上找到 。

翻译自: https://www.freecodecamp.org/news/spreadsheets-and-rowsets-getting-you-down-fd6ff7599052/

json数据转换成表格

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/395319.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mxm智能教育机器人无法智能对话_零代码使用腾讯TBP打造智能对话机器人

点击观看大咖分享心疼你独自一人承担生活的苦难,寂寞夜里陪伴你的只剩无人倾诉的压抑和无处安放的焦虑。养个宠物,它却不能get到你的“宠言宠语”。找个伴侣,还要浪费吵架的时间和精力。回到家里,只能浸泡在“循环唠叨式“母爱的沐…

MyGeneration代码生成工具

使用MyGeneration 生成代码:转自http://www.cnblogs.com/jack-liang/archive/2011/08/18/2144066.html我们经常用数据访问层和业务逻辑层,用MyGeneration就可以自动生成这些代码,我们可以不用手动写代码了。比如数据访问层,我们需…

数据库部分重点内容回顾

1.什么是聚集索引? 树形结构将数据组织和存储起来,起到加速查询的效果 2.主键索引怎么添加? (1)聚集索引(主键索引)的添加方式,创建时添加 方式一: Create table t1( id int primary key, ) 方式二: Create table t1( Id int, Primary key(id) ) (2)唯一索引创建时添加: 方式…

keytool 错误: java.io.IOException: Keystore was tampered with, or password was incorrect

1.这里需要输入的密码不是证书的密码执行keytool -import -keystore - file 这个命令提示需要输入密码进入jdk的bin目录,执行以下脚本,keytool -import -alias saltapi -keystore /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre…

怎么更换锁定计算机的图片,Win10系统下怎样对锁定界面的背景图片进行更换

用户在唤醒睡眠状态的win10系统时,最先看到就是锁定界面。在界面中,一般有时间日期、星期几,及默认的背景图片。那么,win10系统锁定界面中的背景图片可以修改吗?下面,小编就给大家分享Win10系统更换锁定界面…

输电线路巡检机器人PPT_“高空大师”来了!架空输电线路智能巡检机器人在宁波投运...

“鄞州区220千伏天田4480线一切正常……”17日上午,随着一台智能巡检机器人稳稳地停靠在铁塔边,标志着我省首台架空输电线路智能巡检机器人在宁波率先投入运行,为电网安全运行请来了一位“高空大师”。近年来,无人机代替电力工人巡…

HDU 6325 Problem G. Interstellar Travel(凸包)

题意: 给你n个点,第一个点一定是(0,0)&#xff0c;最后一个点纵坐标yn一定是0&#xff0c;中间的点的横坐标一定都是在(0,xn)之间的 然后从第一个点开始飞行&#xff0c;每次飞到下一个点j&#xff0c;你花费的价值就是xi*yj-xj*yi&#xff0c;并且这里每一次飞行必须满足xi<…

UIView封装动画--iOS利用系统提供方法来做关键帧动画

iOS利用系统提供方法来做关键帧动画 ios7以后才有用。 /*关键帧动画options:UIViewKeyframeAnimationOptions类型*/[UIView animateKeyframesWithDuration:5.0 delay:0 options: UIViewAnimationOptionCurveLinear| UIViewAnimationOptionCurveLinear animations:^{//第二个关键…

JavaScript —从回调到异步/等待

JavaScript is synchronous. This means that it will execute your code block by order after hoisting. Before the code executes, var and function declarations are “hoisted” to the top of their scope.JavaScript是同步的。 这意味着它将在提升后按顺序执行代码块。…

关于解决工作中的自动化环境搭建的解决方案(序)

时间&#xff1a;2015~2017 之前的自动化搭建平台&#xff1a;robotest 安装工具&#xff1a;jdk1.8,robotest 这种工具反正超级好用&#xff0c;华为方搞得工具&#xff0c;前台操作超级傻瓜。会点xpatch&#xff0c;一些东西根本不在话下。但是坑爹的就是&#xff0c;出了外包…

xshell安装mysql步骤_mysql主从复制

前期提要&#xff1a;三年前双11买的阿里云今年到期了&#xff0c;win2012的&#xff0c;上面mysql数据库里记着自己的一些记账数据&#xff0c;上一年双11买了腾讯云的&#xff0c;centos7.7, 想学学MYSQL的复制功能&#xff0c;今天趁着无BUG可撸&#xff0c;试着配置了一下&…

大专学计算机维修,《计算机维修与网络工程》大专学历班

语文、数学、计算机英语、公文写作等办公自动化指法训练、英文打字、智能拼音及高速五笔字型中文打字、windows操作、Word2003文字处理软件、Excel2003电子表格、Powerpoint2003幻灯片制作、Internet网络的上网方法、浏览、下载、电子邮件收发等。本班学习完毕&#xff0c;可独…

webpack指定第三方模块的查找路径

通常我们会使用一些地方模块在我们的项目中&#xff0c;比如bootstrap import bootstrap 导入的bootstrap默认会查找当前目录的node_modules文件&#xff0c;但是如果这个文件没有&#xff0c;会依次往上级模块查找&#xff0c;直到到C盘的根目录为止&#xff0c;可以通过webpa…

我的第一个安卓应用程序_我如何设计我的第一个应用程序

我的第一个安卓应用程序by Daniel Novykov丹尼尔诺维科夫(Daniel Novykov) 我如何设计我的第一个应用程序 (How I Designed My First App) This is a story about building a product, what went wrong, and how it changed my career into Design.这是一个有关构建产品&#…

Appium——主从控制执行

1.客户端(Eclipse)机器A&#xff0c; 服务端(appium、Genymotion)机器B 2.设置Appium&#xff0c;Server Address为192.168.17.123&#xff0c;重新启动Appium 3.在客户端机器A浏览器中输入&#xff1a;http://192.168.17.123:4723/wd/hub&#xff0c; 说明配置成功。 JAVA代码…

Python学习-03(集合,文件,编码)

上周复习&#xff1a; 列表增删改查 元祖是可读列表 字符串操作 字典是无序的&#xff0c;通过key来找值。字典可以嵌套列表和字典 本周内容&#xff1a;集合--文件---字符编码 集合引入&#xff1a; #随机生成20个小于20的数&#xff0c;输出所有的数&#xff0c;# 要求重复…

安装centos7失败认不到硬盘_CentOS7 用U盘安装卡住无法进入安装界面解决方案

使用U盘安装Centos系统找不到U盘解决方案补充&#xff1a;1、制作U盘启动盘请参考&#xff1a;使用UltraISO(软碟通)制作ubuntu U盘启动盘如果你安装centos7出现了下图这种情况不用担心&#xff0c;是因为安装centos7时找不到U盘稍等一下&#xff0c;如下图等到出现命令行时。输…

Django横向二级导航栏(鼠标悬空事件)

1 <!DOCTYPE html>2 <html lang"en" xmlns"http://www.w3.org/1999/html">3 <head>4 <meta charset"UTF-8">5 <title>{% block title %} base模板 {% endblock title%}</title>6 <style >…

浙江大学计算机学院1702班,测控1702:传道授业解惑 此间师者真情

2017年9月11日晚8:00&#xff0c;电气与信息工程学院测控技术与仪器1702班在德智学生公寓的天台上开展了一场别开生面的班主任见面交流会。测控1702班班主任文一章博士、电气院2017级本科辅导员金晶老师以及测控1702班的同学们参加了此次见面会。测控1702班班主任文一章1991年出…

通过小程序给公众号传递消息_多输入现场消息传递应用程序概念

通过小程序给公众号传递消息by Dawid Woldu戴维德沃尔杜(Dawid Woldu) 多输入现场消息传递应用程序概念 (A multi-input field messaging app concept) Some time ago I shared in a Medium article the idea for context aware messenger app. The idea challenged the desig…