jsonparsingjqjsonparser

jq - Cannot index string with string "key"


I have a JSON file, which contains similar records like following:

  {
    "timeZone": "+0200",
    "deviceCode": 202590286,
    "type": 8,
    "version": 1622385523034,
    "recordId": "TkgTDAAAAAAIAAAArF62vXkBAAA=",
    "dataId": 0,
    "healthDataSource": 0,
    "appType": 1,
    "startTime": 1622385516204,
    "endTime": 1622385516204,
    "samplePoints": [
      {
        "mergedFlag": 0,
        "unit": "0",
        "startTime": 1622385516204,
        "endTime": 1622385516204,
        "value": "{\"age\":29,\"basalMetabolism\":2266.0,\"bmi\":34.0,\"bodyAge\":38,\"bodyFatRate\":33.20000076293945,\"bodyScore\":67.0,\"bodySize\":5,\"bodyWeight\":115.19999694824219,\"boneSalt\":3.989405632019043,\"extendAttribute\":\"0\",\"gender\":1,\"heartRate\":84,\"height\":184,\"moisture\":51.61684036254883,\"moistureRate\":44.8062858581543,\"muscleMass\":72.9608154296875,\"pole\":1,\"proteinRate\":21.34735107421875,\"skeletalMusclelMass\":42.30829620361328,\"visceralFatLevel\":20.0}",
        "key": "WEIGHT_BODYFAT_BROAD"
      }
    ]
  },
 {
    "timeZone": "+0200",
    "deviceCode": 202576998,
    "type": 7,
    "version": 1622408526036,
    "recordId": "ZhQTDAAAAAAHAAAAIAvJvXkBAAA=",
    "dataId": 0,
    "healthDataSource": 0,
    "appType": 1,
    "startTime": 1622386740000,
    "endTime": 1622386800000,
    "samplePoints": [
      {
        "mergedFlag": 0,
        "unit": "0",
        "startTime": 1622386740000,
        "endTime": 1622386800000,
        "value": "78.0",
        "key": "DATA_POINT_DYNAMIC_HEARTRATE"
      }
    ]
  },
 {
    "timeZone": "+0800",
    "deviceCode": 202590286,
    "type": 8,
    "version": 1622615424878,
    "recordId": "TkgTDAAAAAAIAAAAAHxqy3kBAAA=",
    "dataId": 0,
    "healthDataSource": 0,
    "appType": 1,
    "startTime": 1622615424000,
    "endTime": 1622615424000,
    "samplePoints": [
      {
        "mergedFlag": 0,
        "startTime": 1622615424000,
        "endTime": 1622615424000,
        "value": "{\"age\":29,\"bodyWeight\":114.3,\"extendAttribute\":\"0\",\"gender\":1,\"height\":184,\"pole\":1,\"weightDivision\":2}",
        "key": "WEIGHT_BODYFAT_BROAD"
      }
    ]
  },

I try to use map(select(.key == "WEIGHT_BODYFAT_BROAD")) to filter this type of records, but got error message.

jq: error (at :22): Cannot index string with string "key" jq: parse error: Expected value before ',' at line 22, column 4 exit status 5


Solution

  • If your snippet is the full file, it is missing an array around all the entries. A JSON file has to contain one "element" at "root", this can be either an object ({...}) or an array ([...]).

    In your case the JSON consists of multiple objects, so you have to wrap them in an array. Try to insert [ at the beginning of the file and ] at the very end, don't change anything else.

    Then try your call to jq again.