jsonjqfromjson

Parsing string with fromjson and collapsing into the parent in JQ


I am attempting to parse out the following json array below. The activities object is a string and I have successfully been able to parse it out with the following in jq.

[
 {
    "id": 101,
    "created_at": "1987-10-12 03:20:22.903",
    "updated_at": "1987-10-12 01:20:36.019",
    "activities": "{\"hero\": \"batman\", \"weapon\": \"sword\", \"ts\": null, \"remote\": \"1\",\"game\": \"joker\", \"image\": \"bold\"}"
 },
 {   
    "id": 102,
    "created_at": "2022-10-12 11:20:22.903724",
    "updated_at": "2022-10-12 11:20:36.019043",
    "activities": "{\"hero\": \"superman\", \"weapon\": \"cape\", \"ts\": null, \"remote\": \"2\",\"game\": \"batman\", \"image\": \"kind\"}"
  }
]

The following command allows me to parse out the string object but I haven't quite figured out how to get it back into the original array.

jq '.[].activities | fromjson?' test.json

Output:

{
  "hero": "batman",
  "weapon": "sword",
  "ts": null,
  "remote": "1",
  "game": "joker",
  "image": "bold"
}
{
  "hero": "superman",
  "weapon": "cape",
  "ts": null,
  "remote": "2",
  "game": "batman",
  "image": "kind"
}

I tried several variances of the += and |= operators to add back to the original without any luck.

jq '.[].activities |= fromjson? | select( . != "")' Bypassed any empty values with the select command.

This yields no results for the activities object when I run it. It brings the original id, created_at, and updated_at forward but nothing else.

Appreciate any help you can offer. Thanks guys.

Preferred Output

[
 {
    "id": 101,
    "created_at": "1987-10-12 03:20:22.903",
    "updated_at": "1987-10-12 01:20:36.019",
    "hero": "batman",
    "weapon": "sword",
    "ts": null,
    "remote": "1",
    "game": "joker",
    "image": "bold"
  },
  {
    "id": 102,
    "created_at": "2022-10-12 11:20:22.903724",
    "updated_at": "2022-10-12 11:20:36.019043",
    "hero": "superman",
    "weapon": "cape",
    "ts": null,
    "remote": "2",
    "game": "batman",
    "image": "kind"
  }
]

Solution

  • Something like this should be enough:

    map(del(.activities) + (.activities | fromjson))
    

    Online demo