如何使用JMESPATH合并JSON?

时间:2019-02-11 22:11:24

标签: json merge jmespath

所以事情是,我有一个看起来像这样的JSON:

{
"country": "USA",
"states": [
    {
        "stateName": "California",
        "timeZone": "UTC-8",
        "cities": [
            {
                "cityName": "Los Angeles"
            },
            {
                "cityName": "San Diego"
            }
        ]
    },
    {
        "stateName": "Texas",
        "timeZone": "UTC-8",
        "cities": [
            {
                "cityName": "Houston"
            },
            {
                "cityName": "Dallas"
            }
        ]
    }
]

}

(那个json只是一个例子,不要当真)

我需要做的是列出所有城市,还要从父级中获取“ stateName”字段,然后以某种方式将其放入city对象中,从而得到如下结果:

[
{
    "stateName": "California",
    "cityName": "Los Angeles"
},
{
    "stateName": "Texas",
    "cityName": "Houston"
},
{
    "stateName": "Texas",
    "cityName": "Dallas"
},
{
    "stateName": "California",
    "cityName": "San Diego"
}

]

我尝试以几种不同的方式使用内置合并功能,但是除了该功能的文档不是很直观之外,我没有得到任何结果。

我的一次失败尝试:

merge(`states[].cities[]`, `states[].{stateName: stateName}`)

有什么想法吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

您不能使用jmespath做到这一点。检查一下:https://github.com/jmespath/jmespath.js/issues/22#issuecomment-394157797

但是,您现在可以执行以下操作:

states[].{stateName: stateName, cities: cities[].cityName}[]

产生如下输出:

[
  {
    "stateName": "California",
    "cities": [
      "Los Angeles",
      "San Diego"
    ]
  },
  {
    "stateName": "Texas",
    "cities": [
      "Houston",
      "Dallas"
    ]
  }
]

答案 1 :(得分:0)

我找到了一个解决方案,但是您需要在此处输入一些硬编码值:

states[].{stateName: stateName, cities: cities[]}[] | @[*].{stateName: {stateName: stateName}, cities: cities} | @[*].[merge(stateName,cities[0]),merge(stateName,cities[1])][]

它给出:

[
  {
    "stateName": "California",
    "cityName": "Los Angeles"
  },
  {
    "stateName": "California",
    "cityName": "San Diego"
  },
  {
    "stateName": "Texas",
    "cityName": "Houston"
  },
  {
    "stateName": "Texas",
    "cityName": "Dallas"
  }
]