How shell(bash) retrieves multiple values from the JSON string and substitutes them into environment variables

Asked 1 years ago, Updated 1 years ago, 311 views

I'd like to get multiple values from the following JSON string and substitute them into the environment variable.
It didn't work.

Shell didn't work as expected

json_string='{"name":"John", "age":30, "city":"New York"}'
read name age<<<$(echo$json_string | jq-r'.name, .age')
echo$name
echo$age

Run Results

(venv)xx@xxxx$
(venv)xx@xxxx$json_string = '{ "name" : "John", "age" : 30, "city" : "New York" }'
(venv)xx@xxxx$read name age<<$(echo$json_string | jq-r'.name, .age')
(venv)xx@xxxx$echo$name
John
(venv)xx@xxxx$echo$age

(venv)xx@xxxx$

John
to $name $ange to 30
How do I store the ?

bash shell

2023-02-23 20:42

1 Answers

For example, use xargs.

$read name age<<$(echo "$json_string" | jq-r'.name, .age' | xargs)
$ echo$name
John
$ echo$age
30

Alternatively, you can do join() within the jq command.

$read name age<<$(echo "$json_string"|jq-r'[.name, .age]|join("")')
$ echo$name
John
$ echo$age
30


2023-02-23 22:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.