In this tutorial, we will go over how to use jq to transform xml data as well as any other data format, including binary formats. The steps assumes a basic familiarity with jq and unix shell pipelines. If you’re unfamiliar with jq, check out the first part of the mastering jq series.
XML
In this section, we’ll use jq to transform xml data.
Setup
Consider the following data and let it be stored in before.json
:
{
"root": {
"a": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
]
}
}
and we need to double each number so it looks like:
{
"root": {
"a": [
2,
4,
6,
8,
10,
12,
14,
16,
18,
20
]
}
}
Then, with jq, we can do:
cat before.json |\
jq '{root: {a: (.root | .a | map(. * 2))}}'
Simple XML
Let us consider the same problem, but the data is instead encoded as xml. Let it be in a file, before.xml
<?xml version="1.0" encoding="utf-8"?>
<root>
<a>1</a>
<a>2</a>
<a>3</a>
<a>4…