如何用jq提取JSON所有键值对生成可eval的变量赋值语句
Solution to Convert Nested JSON to Shell Variable Assignments
Got it, let's solve this problem. You need to flatten your nested JSON into shell-friendly variable assignments, where nested keys are joined with underscores. Here's how to do it with jq:
The JQ Command
Run this command against your input JSON (replace input.json with your file path, or pipe JSON directly into it):
jq -r ' [ paths(scalars) as $p | ($p | join("_")) + "=\"" + (getpath($p) | tostring | gsub("\""; "\\\"")) + "\"" ] | join(" ") ' input.json
How It Works
Let's break down each part to understand what's happening:
paths(scalars): This recursively finds all paths to scalar values (strings, numbers, booleans, null) in your JSON. For your sample input, this gives paths like["key1", "data3"].$p | join("_"): Joins the path components with underscores to create the variable name (e.g.,key1_data3).getpath($p): Fetches the value associated with the path (e.g.,"some data").tostring | gsub("\""; "\\\""): Converts the value to a string and escapes any double quotes in the value (so values likehe said "hi"becomehe said \"hi\", which is safe for shell variables).[ ... ] | join(" "): Collects all variable assignments into an array and joins them with spaces to produce a single line ready foreval.
Sample Output
For your input JSON, this command will output exactly what you want:
data1="some data" data2="some data" key1_data3="some data" key1_data4="some data" key2_data5="some data"
You can pipe this directly to eval to set the variables in your shell:
eval $(jq -r ' [ paths(scalars) as $p | ($p | join("_")) + "=\"" + (getpath($p) | tostring | gsub("\""; "\\\"")) + "\"" ] | join(" ") ' input.json)
Content of the question来源于stack exchange,提问作者anton1
相关产品推荐
相关产品推荐

