2

I'm trying to use jq to parse a JSON file for me. I want to get a value from a definition header into the output data in place of an index. A simplified example:

{
  "header": {
    "type": {
      "0": {
             "name": "Cats"
           },
      "3": {
             "name": "Dogs"
           }
    }
  },
  "data": [
    {
      "time": "2019-01-01T02:00:00Z",
      "reading": { 
                   "0": {"value": 90, "note": "start" },
                   "3": {"value": 100 }
                 } 
    }
  ]
}

Using a jq command like jq '.data[] | {time: .time, data: .reading[]}' gives me:

  "time": "2019-01-01T02:00:00Z",
  "data": {
    "value": 90,
    "note": "start"
  }
}
{
  "time": "2019-01-01T02:00:00Z",
  "data": {
    "value": 100
  }
}

I need to get "Cats" or "Dogs" into the result, heading towards an SQL insert.

Something like:

{
  "time": "2019-01-01T02:00:00Z",
  "data": {
    "type: "Cats",      <- line added
    "value": 90,
    "note": "start"
  }
}
...

Or better yet:

{
  "time": "2019-01-01T02:00:00Z",
  "Cats": {                    <- label set to "Cats" instead of "data"
    "value": 90,
    "note": "start"
  }
}
...

Is there a way I can get - what I see as the array index "0" or "3" - to be added as "Cats" or "Dogs"?

0

1 Answer 1

1

Using the built-in function, INDEX, for creating a dictionary allows a straightforward solution as follows:

(.header.type
 | INDEX(to_entries[]; .key)
 | map_values(.value.name)) as $dict
| .data[] 
| (.reading | keys_unsorted[]) as $k
| {time} + { ($dict[$k]) : .reading[$k] }

Output

{
  "time": "2019-01-01T02:00:00Z",
  "Cats": {
    "value": 90,
    "note": "start"
  }
}
{
  "time": "2019-01-01T02:00:00Z",
  "Dogs": {
    "value": 100
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.