You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:

  1. 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"].
  2. $p | join("_"): Joins the path components with underscores to create the variable name (e.g., key1_data3).
  3. getpath($p): Fetches the value associated with the path (e.g., "some data").
  4. tostring | gsub("\""; "\\\""): Converts the value to a string and escapes any double quotes in the value (so values like he said "hi" become he said \"hi\", which is safe for shell variables).
  5. [ ... ] | join(" "): Collects all variable assignments into an array and joins them with spaces to produce a single line ready for eval.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:10:02