Windows' cmd
capabilities are very limited and support for JSON certainly isn't one of them, so I would advice against creating a batch-script! I would highly recommend the command-line tool xidel though. It prettifies by default.
Stdin:
ECHO {"a":1,"b":2,"c":3} | xidel -se "$json"
{
"a": 1,
"b": 2,
"c": 3
}
(If the input is JSON, xidel
will parse and assign it to the (internal) global variable $json
)
File/url:
xidel -s "input.json" -e "$json"
#or
xidel -s "https://[...]" -e "$json"
#or
xidel -se "json-doc('file-or-url')"
Write to file:
xidel -s "input.json" -e "$json" > output.json
#or
xidel -s "input.json" -e "file:write('output.json',$json,{'method':'json','indent':true()})"
#or
xidel -se "file:write('output.json',json-doc('input.json'),{'method':'json','indent':true()})"
Process multiple files:
FOR %A IN (*.json) DO @xidel -s %A -e "$json" > %~nA_pretty.json
While this would work for lots of JSON-files in a directory, it's also extremely slow, because xidel
is called for each and every JSON-file.
xidel
can do this much more efficiently with the integrated EXPath File Module.
xidel -se "file:list(.,false,'json')"
This returns a bare list of all JSON-files in the current directory.
(Equivalent of DIR *.json /B
and FOR %A IN (*.json) DO @ECHO %A
)
xidel -se "file:list(.,false,'json') ! file:read-text(.)"
#or
xidel -se "for $x in file:list(.,false,'json') return file:read-text($x)"
Both commands return the content of each JSON-file in the current directory.
(Equivalent of FOR %A IN (*.json) DO @TYPE %A
)
xidel -se "file:list(.,false,'json') ! json-doc(.)"
#or
xidel -se "for $x in file:list(.,false,'json') return json-doc($x)"
Both commands return the prettified parsed JSON content of each JSON-file in the current directory.
(Equivalent of FOR %A IN (*.json) DO @xidel -s %A -e "$json"
, but much faster!)
xidel -se "file:list(.,false,'json') ! file:write(substring-before(.,'.json')||'_pretty.json',json-doc(.),{'method':'json','indent':true()})"
#or
xidel -se "for $x in file:list(.,false,'json') return file:write(substring-before($x,'.json')||'_pretty.json',json-doc($x),{'method':'json','indent':true()})"
Both commands write the prettified parsed JSON content of each JSON-file in the current directory to a new file with a filename which ends with "_pretty".
The final command prettified (with the necessary escape-characters):
xidel -se ^"^
for $x in file:list(.,false,'json') return^
file:write(^
substring-before($x,'.json')^|^|'_pretty.json',^
json-doc($x),^
{'method':'json','indent':true()}^
)^
"
Please download a xidel
binary from the recommended "Development"-branch to use these queries (and json-doc()
in particular).
If you insist on using xidel 0.9.8
, then use json(file:read-text($x))
instead of json-doc($x)
.