17.34 XML YAML JSON Conversion

20220912

Use the yq command to convert between YAML, JSON, and XML. The source code is available from command from https://github.com/mikefarah/yq with the documentation at https://mikefarah.gitbook.io/yq/.

To convert XML to YAML use --input-format string= (-p=) to specify xml as the input format and --output-format string= (-o=) to specify the output format as json

yq -p=xml -o=json stations.xml > stations.json

See Section 17.35 for details of the yq command.

A more sophisticated example extracts iradio entries from RhythmBox’s ~/.local/share/rhythmbox/rhythmdb.xml file to convert to json. Then use radiotray-ng’s Bookmark Editor under Preferences to import those JSON entries into the file ~/.config/radiotray-ng/bookmarks.json (or use a text editor to do so).

We can extract all of the iradio entries from the RhythmBox database with:

cat ~/.local/share/rhythmbox/rhythmdb.xml |
    yq -p=xml -o=json '.rhythmdb.entry[] | select(.+type == "iradio") | {"name":.title, "url": .location}'

The following will extract entries which have a specific genre into a json format consisting of name and url as required by radiotray.

cat ~/.local/share/rhythmbox/rhythmdb.xml |
    yq -p=xml -o=json '.rhythmdb.entry[] | select(.+type == "iradio") | select(.genre == "Guitar") | {"name":.title, "url": .location}'

Some manual processing still required, including commas between entries and grouping into the genre/group. Work in progress to get closer to what is required for radiotray.



Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0