Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用jq创建经过转换的嵌套JSON元素?_Json_Jq - Fatal编程技术网

如何使用jq创建经过转换的嵌套JSON元素?

如何使用jq创建经过转换的嵌套JSON元素?,json,jq,Json,Jq,我有一个包含嵌套元素的JSON文件,我正试图将其处理为一个未列出的JSON文件。我该怎么做 使用js,我尝试分离百分比,这是我能够做到的。我不知道如何重命名百分比字段。我见过这样的例子:value.gender或value.grade应该起作用,但我也不确定如何将它们结合起来 jq'.data[]|.id作为$id |(.demographics[]|.percentage作为$percentage |.gender作为$gender |.grade作为$grade |{“id”:$id,“p

我有一个包含嵌套元素的JSON文件,我正试图将其处理为一个未列出的JSON文件。我该怎么做

使用js,我尝试分离百分比,这是我能够做到的。我不知道如何重命名百分比字段。我见过这样的例子:value.gender或value.grade应该起作用,但我也不确定如何将它们结合起来


jq'.data[]|.id作为$id |(.demographics[]|.percentage作为$percentage |.gender作为$gender |.grade作为$grade |{“id”:$id,“percentage”:$percentage})test2.json
从这里,我希望能够将百分比字段重命名为性别和等级值。然后我想按id分组

以下是原始JSON文件(test2.JSON):

以下是我的期望:


{
         "id": "abc",
         "students": "elementary",
         "demo_K-2_unspecified": "0.1",
         "demo_K-2_male": "0.5",
         "demo_K-2_female": "0.4",
         "demo_3-6_male": "0.3",
         "demo_3-6_unspecified": "0.6",
         "demo_3-6_female": "0.5",
            },
      {
         "id": "def",
         "students": "midhigh",
         "demo_7-9_unspecified": "0.2",
         "demo_7-9_male": "0.2",
         "demo_7-9_female": "0.6",
         "demo_10-12_male": "0.1",
         "demo_10-12_unspecified": "0.1",
         "demo_10-12_female": "0.8",

      }


对于样本数据,以下过滤器将生成所需的输出:

.data[]
| {id, students} as $ix
| .demographics
| map( {"demo_\(.grade)_\(.gender)": .percentage} )
| $ix + add
这里的主要思想是使用
map
创建键值对列表,这样就可以使用
add
轻松创建复合对象

作为一个班轮
这是一个很好的例子。$ix返回两个字典,add返回两个字典将第一个ix添加到第一个映射,将第二个ix添加到第二个映射?我很难相信这一点。我隔离了$ix输出和map add输出以查看数据。我感兴趣的是通过ix+部分映射“泄漏”的数组。有道理。一个班轮有帮助。所以字典列表之间的+符号就像矩阵合并。
.data[]
| {id, students} as $ix
| .demographics
| map( {"demo_\(.grade)_\(.gender)": .percentage} )
| $ix + add
jq '.data[] | {id,students} + (.demographics | map( {"demo_\(.grade)_\(.gender)": .percentage} ) | add)' test2.json