1

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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_]*$

3 Comments

jq -n '{\n currentBlock: 4769045,\n highestBlock: 7063981,\n knownStates: 15306625,\n pulledStates: 15306625,\n startingBlock: 0\n}'
The Q as shown by SO does not mention anything about newlines or '\n` strings. Please clarify the Q.
Line breaks would not cause problems, but literal "\n" strings would. Please see the separate answer about handling such strings.
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.