如何从JSON读取嵌套数组元素?

如何从JSON读取嵌套数组元素?,json,jq,nested-lists,jsonpath,Json,Jq,Nested Lists,Jsonpath,我需要解析带有嵌套数组元素的JSON并提取值 我不知道如何使用嵌套数组来设置输出JSON中属性的值 这是输入: [{ "name": "book1", "id": 18789, "locations": [{ "state": "mystate", "phone&quo

我需要解析带有嵌套数组元素的JSON并提取值

我不知道如何使用嵌套数组来设置输出JSON中属性的值

这是输入:

  [{
        "name": "book1",
        "id": 18789,
        "locations": [{
            "state": "mystate",
            "phone": 8877887700
        }, {
            "state": "mystate1",
            "phone": 8877887701
        }]
    },
    {
        "name": "book2",
        "id": 18781,
        "locations": [{
            "state": "mystate3",
            "phone": 8877887711
        }, {
            "state": "mystate4",
            "phone": 8877887702
        }]
    }]
这是预期的产出:

{
    "name": ["book1", "book2"],
    "id": ["18789", "18781"],
    "states": [
        ["mystate", "mystate"],
        ["mystate3", "mystate4"]
    ]
}
我尝试使用以下JSLT表达式:

{
  "name" : [for (.)
               let s = string(.name)
               $s],
"id": [for (.)
               let s = string(.id)
               $s],
"states": [for (.)
               let s = string(.locations)
               $s]
}  
但是我不知道在这种情况下如何设置
状态
,以便在输出中获得状态值


使用JQ或JSONPath的解决方案也可能有所帮助。

使用JQ会更容易

{
名称:映射(.name),
id:map(.id),
州:地图(.locations |地图(.state))
}

有了JQ,事情会更简单

{
名称:映射(.name),
id:map(.id),
州:地图(.locations |地图(.state))
}

在JSLT中,您可以这样实现它:

{
  "name" : [for (.) .name],
  "id": [for (.) .id],
  "states": flatten([for (.) [for (.locations) .state]])
} 
{
  "name" : .[].name,
  "id": .[].id,
  "states": .[].locations.[].state
} 
正如您所看到的,
表示
键的实现有点笨拙。我曾考虑过让路径表达式遍历数组,如果我们将其添加到语言中,它可以实现如下:

{
  "name" : [for (.) .name],
  "id": [for (.) .id],
  "states": flatten([for (.) [for (.locations) .state]])
} 
{
  "name" : .[].name,
  "id": .[].id,
  "states": .[].locations.[].state
} 

在JSLT中,您可以这样实现它:

{
  "name" : [for (.) .name],
  "id": [for (.) .id],
  "states": flatten([for (.) [for (.locations) .state]])
} 
{
  "name" : .[].name,
  "id": .[].id,
  "states": .[].locations.[].state
} 
正如您所看到的,
表示
键的实现有点笨拙。我曾考虑过让路径表达式遍历数组,如果我们将其添加到语言中,它可以实现如下:

{
  "name" : [for (.) .name],
  "id": [for (.) .id],
  "states": flatten([for (.) [for (.locations) .state]])
} 
{
  "name" : .[].name,
  "id": .[].id,
  "states": .[].locations.[].state
}