合并内存中的两个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

