4

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!

glytching
  • 44,936
  • 9
  • 114
  • 120
zyang
  • 105
  • 1
  • 8

1 Answers1

5

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.

glytching
  • 44,936
  • 9
  • 114
  • 120
  • Thank you a lot to let me known that it is not available to use the JsonPath configuration to achieve the project+flatten result. I will choose other solution such as using a piece of groovy code as the configuration. @glytching – zyang Feb 22 '19 at 14:10
  • A large part of your answer is describing how to realize project + flatten operation with the **hard code** way, which is obviously not what I'm pursuing in my question. I think pointing out the limitation of JsonPath as the answer is good enough. So please edit your answer and remove the part that is not corresponding to the description of my question in order to avoid misunderstanding by others, and then I will glad to accept your answer. Thank you again! @glytching – zyang Feb 22 '19 at 15:18