'jq error (at <stdin>:25): Cannot index string with string "data1"

I have a json file with data as below :

{
  "0cef7017-e6af-4c92-9e7c-4db1d7afc733": {
    "Show": [
      "TEST1",
      "TEST2"
    ],
    "data1": 12345,
    "data2": 1234,
    "name": "Amit",
    "Ref": "group_1",
    "data3": 123
  },
  "metadata": "ThRsmflXIMA5LVlOI8vJ0OoSokw=",
  "eef75ad4-c733-42ac-9c55-dd5aa2d69fad": {
    "Show": [
      "TEST3",
      "TEST4"
    ],
    "data1": 12345,
    "data2": 1234,
    "name": "Anuj",
    "Ref": "group_2",
    "data3": 123
  }
}

I want an output like :

12345,Amit
12345,Anuj

I tried below command :

cat AV | jq  '.[]|."data1",."name"'
12345
Amit
jq: error (at <stdin>:25): Cannot index string with string "data1"

It is not giving the expected output. It seems it is not parsing completely as data1 string not appearing at metadata



Solution 1:[1]

You can use

cat AV |jq -r 'to_entries[] | select(.key != "metadata") |.value |"\(.data1), \(.name)"'

where the element with key value metadata is removed. Since the error raises due to metadata, which's one the outermost keys , having no sub-element with key name data1 or name

Demo

Solution 2:[2]

You can use recursive descent ...

Filter

[[.. | (.data1?) | select(.!=null)], [.. | (.name?) | select(.!=null)]] 
| transpose[] 
| @csv

Input

{
  "0cef7017-e6af-4c92-9e7c-4db1d7afc733": {
    "Show": [
      "TEST1",
      "TEST2"
    ],
    "data1": 12345,
    "data2": 1234,
    "name": "Amit",
    "Ref": "group_1",
    "data3": 123
  },
  "metadata": "ThRsmflXIMA5LVlOI8vJ0OoSokw=",
  "eef75ad4-c733-42ac-9c55-dd5aa2d69fad": {
    "Show": [
      "TEST3",
      "TEST4"
    ],
    "data1": 12345,
    "data2": 1234,
    "name": "Anuj",
    "Ref": "group_2",
    "data3": 123
  }
}

Output

12345,"Amit"
12345,"Anuj"

Demo

https://jqplay.org/s/l9OGsI3hFq

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Logan Lee