Home > Net >  How to extract values from a json object with spaces using jq
How to extract values from a json object with spaces using jq

Time:12-01

I have the below JSON string with multiple JSON objects. I would like to extract just the id and name from each object and print it.

{
  "users": [
    {
      "id": "1",
      "name": "John Wick",
      "location": "USA"
    },
    {
      "id": "2",
      "name": "Walter White",
      "location": "USA"
    }
  ]
}

I am using the below code to extract the id and name using 'jq'

for key in $(jq -c '.users | .[]' sample.json); do
  id=$(jq -r '.id' <<< "$key");
  name=$(jq -r '.name' <<< "$key")
  echo $id $name
done

But I am getting parsing errors like below. Can someone help me with this?

parse error: Unfinished string at EOF at line 2, column 0

I tried replacing spaces with a combination of special chars and replace again special chars with spaces. It worked for me but I need a better solution than this.

CodePudding user response:

You can use the csv or tsv features of jq - lots of great examples in the man page!

man jq

Try this:

jq -r '.users[] | [.id , .name] | @csv' sample.json

Example output:

$ jq -r '.users[] | [.id , .name] | @csv' sample.json
"1","John Wick"
"2","Walter White"

Or using string interpolation:

$ jq -r '.users[] | [.id, .name] | "\(.[0]) \(.[1])"' sample.json
1 John Wick
2 Walter White

CodePudding user response:

Using 2 read's to capture the values, we can let JQ loop over the objects, and output the id and name. :

#!/bin/bash
jq -r -c '.users[] | .id, .name' /tmp/input3 | while read -r id && read -r name; do
    echo -e "ID: ${id}\t Name: ${name}"
done

Output:

ID: 1    Name: John Wick
ID: 2    Name: Walter White
  • Related