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

合并内存中的两个JSON数组报错,求正确实现方法

Hey, let's figure out where you went wrong and fix this array merging issue with jq.

First, the error you're seeing happens because when you use <<< "$local $org", you're concatenating two JSON arrays with a space—this creates invalid JSON that jq can't parse. Plus, you used the * operator, which is for merging objects, not arrays. To combine arrays, we need the + operator instead.

Here are two reliable ways to merge your local and org arrays into the desired outputJson:

Method 1: Use jq -s with properly separated JSON inputs

The -s (slurp) flag tells jq to read all input JSONs into a single top-level array. We then use + to merge the two sub-arrays inside it. The key is to pass each JSON array as a separate input (not mashed together):

echo -e "$local\n$org" | jq -s '.[0] + .[1]'

Or using here-string syntax with a newline separator:

jq -s '.[0] + .[1]' <<< "$local"$'\n'"$org"

This works because jq -s wraps your two input arrays into [local_array, org_array], then .[0] + .[1] combines all elements from both into one single array.

Method 2: Pass variables directly with --argjson

This is a cleaner approach if you want to explicitly pass your JSON variables to jq without worrying about input formatting:

jq -n '$local + $org' --argjson local "$local" --argjson org "$org"

The -n flag tells jq not to read input from stdin, while --argjson lets you pass valid JSON directly as variables in the jq script. $local + $org then simply concatenates the two arrays.

Example Output

Using your sample array data, the resulting outputJson will look like:

[
  {"account_id":"01C","id":"0XVWKCFV6P9CA5"},
  {"account_id":"CSDTHQ","id":"631QGYBNSF"},
  {"account_id":"BJPKWSH","id":"15BS0XP4F91V6YH4G0PV"},
  {"account_id":"01BKK44V5F6A1FKH60Q0ANX9JX","id":"01BKK44V7"}
]

To recap: use + for array concatenation, and make sure your input JSON is properly formatted (no random spaces between arrays). That's the fix for your original error!

内容的提问来源于stack exchange,提问作者Rajiv Rai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:32:11