#背景
いろいろなAPIを利用していると、JSON形式で取得することが多い。
しかし、JSON形式のデータでは入れ子構造になっていると、構造が見にくいので面倒である。
そこで、Python上でJSONからXMLに変換する方法をネットで探したが、見つからなかったので
忘備録として記述する
#方法
Python上で、JSONからXMLを直接扱う方法を模索したが、発見できなかった。
そこで、(1)JSONからDICT型に変換し、さらに(2)DICT型からXMLに変換する方法を紹介する。
#JSONからDICT型(辞書型)に変換する方法
手順としては
- JSONファイルの呼び出し
- JSONファイルをDICT型へ変換
という流れで行う。
まず、下記の記事と同じように、jsonファイルを用意する
https://qiita.com/wakaba130/items/5f54aed913156dc4438f
jsonFile.json
{
"honoka": {
"BWH": [
78,
58,
82
],
"height": 157
},
"eri": {
"BWH": [
88,
60,
84
],
"height": 162
},
"kotori": {
"BWH": [
80,
58,
80
],
"height": 159
},
"umi": {
"BWH": [
76,
58,
80
],
"height": 159
},
"rin": {
"BWH": [
75,
59,
80
],
"height": 155
},
"maki": {
"BWH": [
78,
56,
83
],
"height": 161
},
"nozomi": {
"BWH": [
90,
60,
82
],
"height": 159
},
"hanayo": {
"BWH": [
82,
60,
83
],
"height": 156
},
"niko": {
"BWH": [
74,
57,
79
],
"height": 154
}
}
このファイルを、pyファイルから呼び出し、dict型に変換する
python.py
#JSONからDICT型への変換
with open('jsonFile.json', 'r') as f:
json_dict = json.load(f) #jsonからdict辞書型ファイルに変換
print(json_dict) # dict型ででてくるけど、ほとんどjsonと変わらない
#DICT型からXMLに変換する
DICT型からXMLに変換する場合には、dicttoxmlというパッケージを利用する。
pipしてパッケージをインストールする。
$ sudo pip install dicttoxml
Collecting dicttoxml
Installing collected packages: dicttoxml
Successfully installed dicttoxml-1.7.4
それで、DICT型のデータを、XMLに出力する
python.py
import json
import dicttoxml
with open('data.json', 'r') as f:
json_dict = json.load(f) #json -> dict
print(json_dict)
xml = dicttoxml.dicttoxml(json_dict)
print(xml)
cmd
$ python hoge.py
<?xml version="1.0" encoding="UTF-8" ?><root><niko type="dict"><height type="int">154</height><BWH type="list"><item type="int">74</item><item type="int">57</item><item type="int">79</item></BWH></niko><nozomi type="dict"><height type="int">159</height><BWH type="list"><item type="int">90</item><item type="int">60</item><item type="int">82</item></BWH></nozomi><eri type="dict"><height type="int">162</height></xml>
これだと少しみにくい
#XMLをBeautifulSoupできれいきれいする
python.py
import json
import dicttoxml
from bs4 import BeautifulSoup
with open('data.json', 'r') as f:
json_dict = json.load(f) #json -> dict
xml = dicttoxml.dicttoxml(json_dict)
soup = BeautifulSoup(xml, "xml")
print(soup.prettify()) #入れ子構造をわかりやすくする魔法
cmd
$ python hoge.py
<?xml version="1.0" encoding="utf-8"?>
<root>
<eri type="dict">
<height type="int">
162
</height>
<BWH type="list">
<item type="int">
88
</item>
<item type="int">
60
</item>
<item type="int">
84
</item>
</BWH>
</eri>
<kotori type="dict">
<height type="int">
159
</height>
<BWH type="list">
<item type="int">
80
</item>
<item type="int">
58
</item>
<item type="int">
80
</item>
</BWH>
</kotori>
<umi type="dict">
<height type="int">
159
</height>
<BWH type="list">
<item type="int">
76
</item>
<item type="int">
58
</item>
<item type="int">
80
</item>
</BWH>
</umi>
<rin type="dict">
<height type="int">
155
</height>
<BWH type="list">
<item type="int">
75