wolfeye
wolfeye

Reputation: 25

command output give object string how to convert it to json using jq

a command gives the following output which is arranged in an object, how to convert it to json using jq?

{\n  currentBlock: 4769045,\n  highestBlock: 7063981,\n  knownStates: 15306625,\n  pulledStates: 15306625,\n  startingBlock: 0\n}

N.B the output isn't json; it contains \n strings.

i used the following to convert it

echo "$output" | jq -R -s -c 'split("\n")' 

but the output wasn't as i expect it

["{"," currentBlock: 4787477,"," highestBlock: 7063981,"," knownStates: 15306625,"," pulledStates: 15306625,"," startingBlock: 0","}",""]

Upvotes: 1

Views: 273

Answers (3)

peak
peak

Reputation: 116720

A generic solution would be to use a tool such as :

$ echo '{ currentBlock: 4479441, highestBlock: 7063981, knownStates: 15306625, pulledStates: 15306625, startingBlock: 0 }' |
    hjson -j
{
  "currentBlock": 4479441,
  "highestBlock": 7063981,
  "knownStates": 15306625,
  "pulledStates": 15306625,
  "startingBlock": 0
}

Upvotes: 0

peak
peak

Reputation: 116720

If the issue here is that the quasi-JSON contains literal "\n" strings, then you could perhaps remove them using sed 's/\\n//g':

$ output='{\n currentBlock: 4769045,\n highestBlock: 7063981,\n knownStates: 15306625,\n pulledStates: 15306625,\n startingBlock: 0\n}'

$ jq -n -f <(sed 's/\\n//g' <<< "$output")

Another possibility might be to use printf, e.g.

$ printf "$output" "" | hjson -j

Both yield valid JSON.

Upvotes: 1

peak
peak

Reputation: 116720

In this particular case, the "output" as originally shown is a valid jq program, so to convert it to JSON, you could simply provide it to the jq processor as a program, e.g.:

jq -n '{ currentBlock: 4479441, highestBlock: 7063981, knownStates: 15306625, pulledStates: 15306625, startingBlock: 0 }'

Output

{
  "currentBlock": 4479441,
  "highestBlock": 7063981,
  "knownStates": 15306625,
  "pulledStates": 15306625,
  "startingBlock": 0
}

Using the -f option

If the quasi-JSON is in a file, say data.txt, then you could simply run:

jq -n -f data.txt

Caveats

This approach will only work if the text happens to be valid as a jq program. In particular, it won't work if any of the keys is an unquoted jq keyword, or does not match the regex:

^[A-Za-z_][A-Za-z0-9_]*$

Upvotes: 0

Related Questions