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 
peak
  • 105,803
  • 17
  • 152
  • 177
Sandeep Sharma
  • 141
  • 1
  • 2
  • 6

4 Answers4

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
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
3

You can use the following jq command:

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

Output:

a=1
b=2
c=3
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • 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 May 02 '16 at 13:26
  • 1
    @bishop I see your point, but let me keep it simple. Readers will still have your answer as an alternative in such cases. – hek2mgl May 02 '16 at 13:32
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.

bishop
  • 37,830
  • 11
  • 104
  • 139
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
C14L
  • 12,153
  • 4
  • 39
  • 52