Home > Enterprise >  Parse jq array iterate and search string regex
Parse jq array iterate and search string regex

Time:09-20

I am working with a JSON below:

{
    "CITY": "JANCOK NJARAN",
    "FATHER": {
        "1": "WEDHUS",
        "2": "ANDRE"
    },
    "MOTHER": {
        "11": "SARAH",
        "22": "EVELYN",
        "33": "MARKONAH"
    }
}

I parse it with jq to read json

file=$(cat config.json)
city=$(echo $file | ./jq '.CITY')
father=$(echo $base_config | ./jq '.FATHER[]')

I have $data :

HE IS WEDHUS FROM JANCOK NJARAN, ALSO MARKONAH

For now i have a lot of problem, i know how to do it with php, but dont know how to do it with bash

what i want is parse the json using jq and search string inside $data with json provided

Expected output is like this.

Search in $data with JSON config :
Found WEDHUS with id 1 , and MARKONAH with id 2

Any help will be appreciated, thanks

CodePudding user response:

I'm not completely sure what you are trying to achieve, but this might help you on the way there:

Traverse the input document using .., and decompose the objects found into an array of key-value pairs using to_entries. Then, filter it by iterating .[] over its items, and selecting only those whose .value, if in turn being strings, is completely contained inside the $data string, which was provided as argument using the --arg option on invocation). The remaining items can then be formatted to your liking, here using string interpolation \(…) to produce strings, and the -r option on invocation to output them in raw format (as opposed to being JSON encoded).

jq -r --arg data "$data" '
  .. | objects | to_entries[]
  | select(.value | strings | inside($data))
  | "Found \(.value) with id \(.key)"
' config.json
Found JANCOK NJARAN with id CITY
Found WEDHUS with id 1
Found MARKONAH with id 33

Demo

If you want to disregard the top level (eg. CITY), prepend .. with .[] |.

To just output a comma-separated list consisting only of all the matching IDs, wrap the whole traversal, filtering, and formatting into a pair of brackets […] turning the whole result stream into an array, then use join with a glue string to concatenate. Additional formatting such as wrapping the final list within parentheses can also be done here, eg. using again string interpolation.

jq -r --arg data "$data" '
  [ .. | objects | to_entries[]
  | select(.value | strings | inside($data)).key
  ] | "(\(join(",")))"
' config.json
(CITY,1,33)

Demo

  • Related