Sandeep Sharma
Sandeep Sharma

Reputation: 141

Parse JSON data into a variable assignment format

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 

Upvotes: 2

Views: 234

Answers (4)

Jeff Mercado
Jeff Mercado

Reputation: 134801

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

Upvotes: 5

bishop
bishop

Reputation: 39354

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.

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 157947

You can use the following jq command:

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

Output:

a=1
b=2
c=3

Upvotes: 3

C14L
C14L

Reputation: 12548

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

Upvotes: 0

Related Questions