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
223 views
in Technique[技术] by (71.8m points)

linux - Combine keyword / value pairs from JSON files into a single JSON for submitting with curl

I want to add an array to the "fields" How can I do that?

how to add a "fields" array?

fields=()
for f in NameData/*.json
do
        Name= cat $f | jq -r '.[] | .Name'
        Value= cat $f | jq -r '.[] | .Value'
        
        fields+= #how? 
        '{
            "name" : "'$Name'",
            "value": "'$Value'"
        },'
done

#output for fields

{
    "name" : "Test"
    "value" : "1"
},
{
    "name" : "Test2"
    "value" : "2"
},
...

Because next to post

function Hi(){
    curl -H "Content-Type: application/json" -X POST -d 
        '{
                    #how to array in fields //while?
            "fields": [
                    {
                        "name": "Test",
                        "value":"'1'",
                    },
                    {
                        "name": "Test2",
                        "value":"'2'",
                    }
                    ...
                ]
        ...
}}

How do I need to give more details? Can you help me? Thanks.

My files here (JSON) like I'm trying to get the name and value

xample.json
[
    ...
    {
        "folder" : "nobody",
        "name": "1TS",
        "value": "2",
        ...
    }
]
example2.json
[
    {
        "name": "TST",
        "value": "4.75",
        ...
    }
]
question from:https://stackoverflow.com/questions/65875235/combine-keyword-value-pairs-from-json-files-into-a-single-json-for-submitting

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

1 Reply

0 votes
by (71.8m points)

Bash arrays are just collections of strings. Probably just collect the key/value pairs and then finish up by formatting it as JSON.

fields=()
for f in NameData/*.json
do
        fields+=$(jq -r '.[] | {name: .name, value: .value}' "$f") 
done

Notice also how you need a command substitution to run a command and assign its output to a variable and how we avoid the useless cat and spend just one jq call to extract both fields.

But probably a much better solution is just to use jq directly.

curl -H "Content-Type: application/json" -X POST -d "$(
    jq -s '{ fields: map({name: .[0].name, value: .[0].value})}' NameData/*.json)"

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

...