bash 如何将xml文件转换为json文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25615541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:16:19  来源:igfitidea点击:

how to convert xml file to json file

jsonxmlbash

提问by lr.

I would like to have an answer on how to save the extract data from my Linux directories to json. I tried saving it to XML file already wherein if I run the script it will generate an XML(data.xml). Now, I don't know how to have in json file.

我想知道如何将我的 Linux 目录中的提取数据保存到 json。我已经尝试将它保存到 XML 文件中,如果我运行脚本,它将生成一个 XML(data.xml)。现在,我不知道如何在 json 文件中使用。

This is my XML template inside my bash script:

这是我的 bash 脚本中的 XML 模板:

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

回答by Yurkee

I'd suggest using xmljsonlib, and code sth. like this:

我建议使用xmljsonlib 和代码…… 像这样:

from collections import OrderedDict
from xmljson import BadgerFish
from json import dumps

def xml_to_json(xml_string):
    bf = BadgerFish(dict_type=OrderedDict)
    return dumps(bf.data(fromstring(xml_string)))