8

I have a JSON file that has this content:

{
  "Message": {
    "greeting": "hello"
  }
}
{
  "Message": {
    "greeting": "Bonjour"
  }
}
{
  "Message": {
    "greeting": "Konnichiwa"
  }
}

I would like to extract only the first Message that has "greeting" : "hello". I can't seem to use an index on it using

cat "$file" | jq -c "."

The above command all returns the three messages. I would like to ask on how to only extract the first message or one by one.

1
  • If your json is always indented that way, you could also do sed '/^}/q' < thatfile which would save having to read it fully or parse the json in there. Mar 11, 2021 at 13:35

2 Answers 2

9

You input file contains several JSON objects. Use -s to read them all into a single array, otherwise jq processes them one by one. Then, you can just print the first one by specifying its index:

jq -cs '.[0]' 
2
5

Assuming that you want the first JSON object which has a greeting key corresponding to the value hello, specifically, not just the first JSON object.

jq -s 'map(select(.Message.greeting == "hello")) | first' file.json

This reads the JSON objects in file.json into an array with -s (--surp). This array is then filtered for any object that contains a .Message.greeting key with value hello. The first of these objects is returned.

With a modified example document,

{
  "Message": {
    "greeting": "Konnichiwa"
  }
}
{
  "Message": {
    "greeting": "hello",
    "id": 1
  }
}
{
  "Message": {
    "greeting": "hello",
    "id": 2
  }
}
{
  "Message": {
    "greeting": "Bonjour"
  }
}

where the id keys were added just to tell two otherwise identical objects apart, the jq command returns

{
  "Message": {
    "greeting": "hello",
    "id": 1
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .