convert data to/from json
In this post, we’ll transform data to/from json using the *-to-json and json-to-* tools from the json-toolkit. Transforming data to/from json allows us to use jq (and other json) tools on (almost) any data.
What are *-to-json and json-to*?
*-to-json and json-to-* are collections of cli tools that transform data from one format to another. For example:
xml-to-json - converts xml on stdin to json on stdout
json-to-yaml - converts json on stdin to yaml on stdout
json-to-logfmt - converts json on stdin to logfmt on stdout
In total there are 12 tools covering 6 formats, plus json.
Each tool takes one format on stdin and returns the same data in a different format on stdout, for example:
cat file.xml | xml-to-json > file.json
Why use *-to-json and json-to*?
In short, because they let you do this:
# extracts the element .key.a[1].b from file.xml as xml
cat file.xml | xml-to-json | jq '.key.a[1].b' | json-to-xml
and
# Provides a structural diff of the xml files
json-diff <(cat a.xml | xml-to-json) <(cat b…