Reputation: 141
I'm writing a more complex transformation with jq, and one of the things I'd like to do is to have a pretty printed JSON inside a string. For example:
echo '{"foo": "bar"}' | jq '{json: {other: .} | tostring}'
gives
{
"json": "{\"other\":{\"foo\":\"bar\"}}"
}
while I'd like to get:
{
"json": "{\n \"other\": {\n \"foo\": \"bar\"\n }\n}"
}
I have also tried tojson
and @json
, but they give the same result as tostring
. Is it possible to do with jq or do I have to resort to some other trickery? Note that I need to have multiple such string with formatted JSON in the output, not just one like in the example.
Upvotes: 3
Views: 5173
Reputation: 141
I ended up writing a simple formatting function:
# 9 = \t
# 10 = \n
# 13 = \r
# 32 = (space)
# 34 = "
# 44 = ,
# 58 = :
# 91 = [
# 92 = \
# 93 = ]
# 123 = {
# 125 = }
def pretty:
explode | reduce .[] as $char (
{out: [], indent: [], string: false, escape: false};
if .string == true then
.out += [$char]
| if $char == 34 and .escape == false then .string = false else . end
| if $char == 92 and .escape == false then .escape = true else .escape = false end
elif $char == 91 or $char == 123 then
.indent += [32, 32] | .out += [$char, 10] + .indent
elif $char == 93 or $char == 125 then
.indent = .indent[2:] | .out += [10] + .indent + [$char]
elif $char == 34 then
.out += [$char] | .string = true
elif $char == 58 then
.out += [$char, 32]
elif $char == 44 then
.out += [$char, 10] + .indent
elif $char == 9 or $char == 10 or $char == 13 or $char == 32 then
.
else
.out += [$char]
end
) | .out | implode;
It adds unnecessary empty lines inside empty objects and arrays, but it's good enough for my purpose. For example (used on its own):
jq -Rr 'include "pretty"; pretty' test.json
where the function is saved in pretty.jq
and test.json
file is:
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"key":"string with \"quotes\" and \\"},"geometry":{"type":"Polygon","coordinates":[[[24.2578125,55.178867663281984],[22.67578125,50.958426723359935],[28.125,50.62507306341435],[30.322265625000004,53.80065082633023],[24.2578125,55.178867663281984]]]}}]}
gives:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"key": "string with \"quotes\" and \\"
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
24.2578125,
55.178867663281984
],
[
22.67578125,
50.958426723359935
],
[
28.125,
50.62507306341435
],
[
30.322265625000004,
53.80065082633023
],
[
24.2578125,
55.178867663281984
]
]
]
}
}
]
}
Upvotes: 4
Reputation: 116750
This:
echo '{"foo": "bar"}' | jq '{other: .}' | jq -Rs '{json: .}'
produces:
{
"json": "{\n \"other\": {\n \"foo\": \"bar\"\n }\n}\n"
}
One way to remove the terminating "\n"
would be to strip it:
echo '{"foo": "bar"}' | jq '{other: .}' | jq -Rs '{json: .[:-1]}'
Upvotes: 4