How to flatten a json with nested lists by Jayway JsonPath?

房东的猫 提交于 2021-02-09 08:27:29

问题


Currently I need to process some json results based on configuration but not hard code.

For example, with the json as follows

{
    data: [{
        orderNo: "CG8310150",
        details: [{
            skuId: 4384,
            amount: 2
        }, {
            skuId: 4632,
            amount: 5
        }]
    }, {
        orderNo: "CG8310151",
        details: [{
            skuId: 4384,
            amount: 3
        }]
    }]
}

I want the result as follows

[{
    orderNo: "CG8310150",
    skuId: 4384,
    amount: 2
}, {
    orderNo: "CG8310150",
    skuId: 4632,
    amount: 5
}, {
    orderNo: "CG8310151",
    skuId: 4384,
    amount: 3
}]

If anyone has the solution with Jayway JsonPath, or has any suggestion of other tools, please let me known.

Thanks for your help!


回答1:


You can project results from that JSON using JsonPath. For example:

  • $['data'][*]['orderNo'] returns:

    ["CG8310150","CG8310151"]
    
  • $['data'][*]['details'][*]['skuId', 'amount'] returns:

    [{"skuId":4384,"amount":2},{"skuId":4632,"amount":5},{"skuId":4384,"amount":3}]
    

But you cannot combine both of those expressions in one pass through JsonPath so you cannot use JsonPath to return your target output.



来源:https://stackoverflow.com/questions/54819775/how-to-flatten-a-json-with-nested-lists-by-jayway-jsonpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!