I use split-newlines-and-parse-stringified-json.jq
to make json, usually from logs, more readable:
It recursively:
- splits strings containing newlines into arrays
- expands escaped tabs into spaces
- expands stringified json
$ echo '{
"foo": 42,
"bar": [
"{\"jq\": \"is fun\"}"
],
"mostly": "[true]",
"and": "look\\n{\"more\":\"json\"}\\n!"
}' |
jq '
def fromjson_obj:
with_entries(. as $s
| try (.value = (.value | fromjson)) catch $s
);
def fromjson_arr:
map(. as $s | try fromjson catch $s);
def split_newlines:
if type=="string" then split("\t") | join(" ") | if contains("\n") then split("\n") | split_newlines else . end
elif type=="object" then fromjson_obj | map_values(split_newlines)
elif type=="array" then fromjson_arr | map(split_newlines)
else .
end;
split_newlines
'
{
"foo": 42,
"bar": [
{
"jq": "is fun"
}
],
"mostly": [
true
],
"and": [
"look",
{
"more": "json"
},
"!"
]
}