Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an XML file to a JSON file

Tags:

json

bash

xml

How do I save the extract data from my Linux directories to JSON? I tried saving it to an XML file already where, if I run the script, it will generate an XML file like "data.xml".

I don't know how to convert it to a JSON file.

This is my XML template inside my Bash script:

file=~/data.xml
  template=" <Data>\n\
  <date>%d</date>\n\
  <time>%d</time>\n\
  <age>%d</age>\n\
  <place>%s</place>\n\
  <name>%d<name>\n\</Data>\n"

  echo '<?xml version="1.0"?>' >> $file
  echo '<List2>' >> $file

template

printf "$template" "$date"\
                    "$time"\
                    "$age"\
                    "$place"\
                    "$name"\$file   
#closing tag
echo '</List>' >> $file
like image 630
lr. Avatar asked Nov 23 '22 13:11

lr.


1 Answers

github.com/mikefarah/yq supports this out of the box:

yq -p=xml -o=json file.xml

You can use jq like expression syntax to chop and change the data if required.

Disclaimer: I wrote yq

like image 173
mike.f Avatar answered Jan 14 '23 04:01

mike.f