2

I am trying to parse JSON data into variable format

[
  {
    "Name" : "a",
    "Value" : "1"
  },
  {
    "Name" : "b",
    "Value" : "2"
  },
  {
    "Name" : "c",
    "Value" : "3"
  }
]

output should be like

a=1
b=2
c=3

This is what I tried, but it is not giving the expected result:

jq '.[].Value' file.txt 
4
  • what did you try with jq? You are probably very close! Commented May 2, 2016 at 12:40
  • jq .[].Name file.txt or jq .[].Value file.txt this is printing key, valye in one go but how to assign value to key Commented May 2, 2016 at 12:50
  • Possible duplicate of Parsing JSON with UNIX tools Commented May 2, 2016 at 12:51
  • cat file.txt |jq -r '.[].Name,.[].Value' I have tried this. Now how can I assign value to key in output? Commented May 2, 2016 at 13:22

4 Answers 4

5

Since you're only printing out two values, it might just be easier to print out the strings directly.

$ jq -r '.[] | "\(.Name)=\(.Value)"' file.txt
Sign up to request clarification or add additional context in comments.

2 Comments

Better than my attempt using a list and then join. I never knew that this kind if string interpolation is possible using jq.
Also ... | .Name + "=" + .Value
3

You can use the following jq command:

jq -r '.[]|[.Name,.Value]|join("=")' file.json

Output:

a=1
b=2
c=3

2 Comments

This answer better represents the expected output, though my answer might be useful if the json format needs preservation through other modifications. Feel free to copy mine into your answer to provide an all-encompassing solution (then I'll delete mine).
@bishop I see your point, but let me keep it simple. Readers will still have your answer as an alternative in such cases.
2

Using jq:

jq 'map({(.Name):.Value})|add|.//={}' < data.json

Produces:

{
  "a": "1",
  "b": "2",
  "c": "3"
}

If you have jq version 1.5+, you can use from_entries instead.

Comments

0

This does it

python3 -c 'import json; print("\n".join(["{}={}".format(x["Value"], x["Name"]) for x in json.load(open("file.json"))]))'

result

a=1
b=2
c=3

1 Comment

A Python solution would not be adequate here, he was specifically looking for a jq solution.

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.