0

I have a json file(test.json) with following structure

[
  {
     "key1" : "value-1",
     "key2" : {
       "key3" : "value3"
     }
  },
  {
     "key1" : "value-2",
     "key2" : {
       "key4" : "value4"
     }
  }
]

I want to covert the file content into following given structure

[
  {
     "key1" : "value-1",
     "key2" : "{\"key3\":\"value3\"}"     // basically the stringyfy form of json
  },
  {
     "key1" : "value-2",
     "key2" : "{\"key4\":\"value4\"}"     // basically the stringyfy form of json
  } 
]

I tried like following, able to convert key2 into stringyfy JSON but not sure how to update into JSON. Whatever references I am getting from existing stackoverflow question, they are just adding new value to the existing json object. I need to read the existing value and modify the same and then update it to same json array

jq -c '.[]' $BUILD_DIR/test.json | while read i; do
    echo $(jq -r '.key2' <<< "$i") | jq '@json' 
done

Following one is working for me if I just need to direct update the key2 value, This might look very obvious one but I am very new to bash script syntax.

jq '( .[]).key2 |= "foo"' $BUILD_DIR/test.json
0

1 Answer 1

2
jq 'map(.key2 |= tojson)'

Output

[
  {
    "key1": "value-1",
    "key2": "{\"key3\":\"value3\"}"
  },
  {
    "key1": "value-2",
    "key2": "{\"key4\":\"value4\"}"
  }
]

Demo on jq play

Sign up to request clarification or add additional context in comments.

1 Comment

Are you sure you want tostring instead of tojson here? I assume that if there were a string in the input, we'd want a JSON-escaped version of that string in the output, instead of just leaving it as-is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.