Python/Python Programming

[ Python ] xml 타입의 데이터 json 으로 변경

Pydole 2023. 4. 24. 13:21

 

 

 

xmltodict 모듈설치

 

pip install xmltodict

 

 

xml sample

 

https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85) 

 

Sample XML File (books.xml)

Table of contents Sample XML File (books.xml) Article 10/27/2016 In this article --> The following XML file is used in various samples throughout the Microsoft XML Core Services (MSXML) SDK. Gambardella, Matthew XML Developer's Guide Computer 44.95 2000-10

learn.microsoft.com

 

 

 

 xml 데이터를 dictionary (json) 타입으로 변경

 

import json
import xmltodict

with open('sample.xml', encoding='utf-8') as f:
    doc = xmltodict.parse(f.read())
                          
json_data = json.loads(json.dumps(doc))
print(json_data)

----------------------------------------------------------------

{'catalog': {'book': [{'@id': 'bk101',
    'author': 'Gambardella, Matthew',
    'title': "XML Developer's Guide",
    'genre': 'Computer',
    'price': '44.95',
    'publish_date': '2000-10-01',
    'description': 'An in-depth look at creating applications \n      with XML.'},
   {'@id': 'bk102',
    'author': 'Ralls, Kim',
    'title': 'Midnight Rain',
    'genre': 'Fantasy',
    'price': '5.95',
    'publish_date': '2000-12-16',
    
 .............
 .............