Home > Enterprise >  Convert value of json from int to string using jq
Convert value of json from int to string using jq

Time:03-31

Given a json that looks something like:

[{"id":1,"firstName":"firstName1","lastName":"lastName1"},
{"id":2,"firstName":"firstName2","lastName":"lastName2"},
{"id":3,"firstName":"firstName3","lastName":"lastName3"}]

What would be the best way to convert the id value from an int to a string and then saving the file?

I have tried:

echo "$(jq -r '[.[] | .id = .id|tostring]' test.json)" > test.json

But that seems to put each entry into a string and adds the backslashes

[
  "{\"id\":1,\"firstName\":\"firstName1\",\"lastName\":\"lastName1\"}",
  "{\"id\":2,\"firstName\":\"firstName2\",\"lastName\":\"lastName2\"}",
  "{\"id\":3,\"firstName\":\"firstName3\",\"lastName\":\"lastName3\"}"
]

CodePudding user response:

| has a lower priority than the assignment (=). The expression .id = .id | tostring is interpreted as (.id = .id) | tostring.

The assignment does change anything and can be removed. The script becomes [ .[] | tostring ], that explains the output (each object is serialized as JSON into a string).

The solution is to use parentheses to enforce the desired order of execution.
The command is:

jq '[ .[] | .id = (.id | tostring) ]' test.json

Do not use process expansion ($(...)) to compose an echo command line. It is inefficient and not needed.

Redirect the output of jq directly to a file. Use a different file than the input file (or it ends up destroying your data).

jq '[ .[] | .id = (.id | tostring) ]' test.json > output.json
  • Related