Can I pass a string variable to jq not the file?

前端 未结 7 1294
春和景丽
春和景丽 2020-12-29 03:58

I want to convert JSON string into an array in bash. The JSON string is passed to the bash script as an argument (it doesn\'t exist in a file).

Is there a way of ach

7条回答
  •  攒了一身酷
    2020-12-29 04:27

    The value of the variable "json_data" that was given in the original question was not valid JSON, so this response still covers both cases (nearly-valid and valid JSON).

    Valid JSON

    If "$json_data" does hold a valid JSON value, then here are two alternatives not mentioned elsewhere on this page.

    --argjson

    For example:

     jq -n --argjson data "$json_data" '$data.key'
    

    env

    If the shell variable is not aleady an environment variable:

    json_data="$json_data" jq -n 'env.json_data | fromjson.key'
    

    Nearly-valid JSON

    If indeed $json_data is invalid as JSON but valid as a jq expression, then you could adopt the tactic illustrated by the following transcript:

    $ json_data='{key:"value"}'
    $ jq -n "$json_data" | jq .key
    "value"
    

提交回复
热议问题