I want to add package dependencies to the package.json
file by bash
script using jq
.
Add new element to existing JSON array with jq
Here is the test script with 5 steps:
#!/bin/bashadd_element_with_jq() { # step 1: Add a new root element "{}" first echo "============= step 1 ================" echo "{}" > "package.json" # step 2: Add a "dependencies" sub element to the root element "{}" echo "============= step 2 ================" # step 3: Add a "foo" package with version "1.1.1" to the "dependencies" echo "============= step 3 ================" jq '. += dependencies {"foo": "1.1.1" }'"package.json" echo "=========== step 3 output ==================" cat "package.json" # step 4: Add a "bar" package with version "2.2.2" to the "dependencies" echo "============= step 4 ================" jq '.dependencies += "bar": "2.2.2"'"package.json" # step 5: If the "foo" package already existed, then update to the latest version. Otherwise, add the "foo" package to the dependencies. echo "============= step 5 ================" jq '.dependencies += "foo": "3.3.3"'"package.json" echo "=========== final output ==================" cat "package.json"}add_element_with_jq
Here is the error:
============= step 1 ============================= step 2 ============================= step 3 ================jq: error: syntax error, unexpected '{', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:. += dependencies { jq: 1 compile error=========== step 3 output =================={}============= step 4 ================jq: error: syntax error, unexpected ':', expecting $end (Unix shell quoting issues?) at <top-level>, line 2:"bar": "2.2.2" jq: 1 compile error============= step 5 ================jq: error: syntax error, unexpected ':', expecting $end (Unix shell quoting issues?) at <top-level>, line 2:"foo": "3.3.3" jq: 1 compile error=========== final output =================={}
Here is the expected output:
=========== step 3 output =================={"dependencies": {"foo": "1.1.1" }}=========== final output =================={"dependencies": {"foo": "3.3.3","bar": "2.2.2" }}
What's wrong in my bash
function, and how to fix the jq
commands?