简体   繁体   中英

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

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM