Home > front end >  How to dump json output to the file using jq?
How to dump json output to the file using jq?

Time:07-26

I am trying to copy certain key:value pairs from a json file to normal text file using jq within a bash script. I am doing:

#!/usr/bin/env bash

TestConfig="[...]/config_test.json"

#create new empty file if it doesn't exist
echo -n "" > test_sample.txt

echo "X=$(jq -r .abc $TestConfig '.' > test_sample.txt)"
echo "Y=$(jq -r .xyz $TestConfig '.' > test_sample.txt)"

But this copies only "values" (only values of .abc and .xyz) to test_sample.txt. But I am expecting:

cat test_sample.txt
X=test1
Y=test2

The config_test.json is:

{
    "abc": "test1",
    "xyz": "test2"
}

Can anyone please let me know what needs to be changed to have expected outcome? The .json file is quite big and I am extracting more key:value pairs from it. Hence any looping way to reduce jq operation time would be helpful.

Thanks in advance.

P.S: Please let me know if any info is missing.

CodePudding user response:

If I understood correctly, you want to convert a JSON object's fields to raw text, following a key=value structure.

Use to_entries to decompose the object, iterate over its items with [], and output a formatted string using the .key and the .value. Make sure the output is raw text using -r:

jq -r 'to_entries[] | "\(.key)=\(.value)"' config_test.json > test_sample.txt
abc=test1
xyz=test2

Demo

  • Related