Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jq - How to read nested array elements from JSON?

I need to parse a JSON with nested array elements and extract the values.

I am not sure how to use the nested array to set the value of an attribute in output JSON.

This is the input:

  [{
        "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
        }]
    }]

And this is the expected output:

{
    "name": ["book1", "book2"],
    "id": ["18789", "18781"],
    "states": [
        ["mystate", "mystate"],
        ["mystate3", "mystate4"]
    ]
}

I am trying to use the following JSLT expression:

{
  "name" : [for (.)
               let s = string(.name)
               $s],
"id": [for (.)
               let s = string(.id)
               $s],
"states": [for (.)
               let s = string(.locations)
               $s]
}  

But I am not sure how to set the states in this case so that I have the value of state in the output.

A solution using JQ or JSONPath may also help.

question from:https://stackoverflow.com/questions/66047747/how-to-read-nested-array-elements-from-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With JQ it'd be easier than that.

{
  name:   map(.name),
  id:     map(.id),
  states: map(.locations | map(.state))
}

Online demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...