概要
pythonでjsonファイルをxmlに変換したくて、dicttoxmlのimportが必要になった。
参考にしたサイトではpipでdicttoxmlをインストールしていたので真似したができず、
代わりにcondaでdicttoxmlをインストールしたらできたので、そのメモを残す。
環境
OS:ubuntu 16.4LTS
Python:2.7.14(Anaconda)
Python:3.5.2
pip:10.0.1(python 2.7)
pipでdicttoxmlをインストール
pip install dicttoxml
をターミナルで実行したがエラー。
出力メッセージは以下の通り。
The directory '/home/USERNAME/.cache/pip/http' or its parent directory
is not owned by the current user and the cache has been disabled. Plea
se check the permissions and owner of that directory. If executing pip
with sudo, you may want sudo's -H flag.
The directory '/home/USERNAME/.cache/pip' or its parent directory is n
ot owned by the current user and caching wheels has been disabled. che
ck the permissions and owner of that directory. If executing pip with
sudo, you may want sudo's -H flag.
Requirement already satisfied: dicttoxml in /usr/local/lib/python2.7/d
ist-packages (1.7.4)
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' comm
and.
sudo pip install dicttoxml
でもエラー。
pip install --upgrade pip
でもエラー。
condaでdicttoxmlをインストール
conda install -c conda-forge dicttoxml
Solving environment: done
==> WARNING: A newer version of conda exists. <==
current version: 4.4.10
latest version: 4.5.11
Please update conda by running
$ conda update -n base conda
## Package Plan ##
environment location: /home/dl-desktop4/anaconda2
added / updated specs:
- dicttoxml
The following packages will be downloaded:
package | build
---------------------------|-----------------
dicttoxml-1.7.4 | py27_0 20 KB conda-forge
openssl-1.0.2p | h470a237_0 3.5 MB conda-forge
certifi-2018.1.18 | py27_0 143 KB conda-forge
------------------------------------------------------------
Total: 3.7 MB
The following NEW packages will be INSTALLED:
dicttoxml: 1.7.4-py27_0 conda-forge
The following packages will be UPDATED:
certifi: 2018.1.18-py27_0 --> 2018.1.18-py27_0 conda-forge
openssl: 1.0.2o-h20670df_0 --> 1.0.2p-h470a237_0 conda-forge
Proceed ([y]/n)?
続けるか聞かれたので、yを入力。
Proceed ([y]/n)? y
Downloading and Extracting Packages
dicttoxml 1.7.4: ####################################################### | 100%
openssl 1.0.2p: ######################################################## | 100%
certifi 2018.1.18: ##################################################### | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
インストール完了。
pythonでjsonファイルをxmlファイルに変換することができた。
json2xml.py
import json
import dicttoxml
from bs4 import BeautifulSoup
with open('sample.json', 'r') as fi:
json_dict = json.load(fi)
# print(json_dict)
xml = dicttoxml.dicttoxml(json_dict)
# print(xml)
soup = BeautifulSoup(xml, "xml")
# print(soup.prettify())
with open('sample.xml', 'w') as fo:
fo.write(soup.prettify())
参考
Anaconda CLOUD の conda-forge / packages / dicttoxml
Python JSON形式のデータを、XMLに変換する