Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert value of json from int to string using jq

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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\"}"
]

>Solution :

| 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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading