본문 바로가기
Python

[Python] - xml to json / json to xml 변환하기

by nam_ji 2025. 1. 17.

xml to json (xml 데이터 json으로 변환)

  • 로직
    더보기
    로직
    
    import json
    import xmltodict
    
    with open("../data/xml_to_json.xml", "r") as f:
        xml_data = f.read()
    
    print(f"\nxml 데이터 파일 읽어와서 출력한 결과: \n{xml_data}")
    
    json_data = json.dumps(xmltodict.parse(xml_data), indent=4)
    
    print(f"\njson 데이터로 변환하여 출력한 결과: \n{json_data}")

1. 모듈 임포트

  • import json
    import xmltodict
  • json: JSON 데이터를 파싱하거나 JSON 문자열로 변환하기 위한 표준 라이브러리.
  • xmltodict: XML 데이터를 Python의 딕셔너리로 변환하거나, 딕셔너리를 XML로 변환하는 외부 라이브러리.

2. xml 파일 열기 및 데이터 읽기

  • with open("../data/xml_to_json.xml", "r") as f:
        xml_data = f.read()
  • open() 함수로 XML 파일을 읽어옵니다.
  • read() 함수로 XML 데이터를 문자열로 읽어옵니다.

3. xml 데이터를 딕셔너리로 변환

  • xmltodict.parse(xml_data)
  • xmltodict모듈의 parse() 함수로 XML 문자열을 Python 딕셔너리로 변환합니다.
  • 이 딕셔너리를 JSON 형식으로 변환할 수 있습니다.

4. 딕셔너리를 json 문자열로 변환

  • json_data = json.dumps(xmltodict.parse(xml_data), indent=4)
  • json 모듈의 dumps() 함수를 사용하여 딕셔너리를 JSON 문자열로 변환합니다.
  • indent 설정으로 JSON 데이터를 들여쓰기 하여 읽기 쉽게 포맷팅합니다. (json 엘리먼트끼리의 레벨을 indent 설정으로 구분하여 사용자가 읽기 쉬워집니다.)

5. json 출력

  • xml과 json 출력
    더보기
    xml 데이터 파일 읽어와서 출력한 결과: 
    <?xml version="1.0" encoding="UTF-8"?>
    <products>
        <product id="101">
            <name>Smartphone</name>
            <category>Electronics</category>
            <price>599.99</price>
            <stock>150</stock>
            <manufacturer>
                <name>BrandX</name>
                <address>123 BrandX St, City, Country</address>
            </manufacturer>
            <features>
                <feature>5G Connectivity</feature>
                <feature>6GB RAM</feature>
                <feature>128GB Storage</feature>
            </features>
        </product>
        <product id="102">
            <name>Laptop</name>
            <category>Electronics</category>
            <price>999.99</price>
            <stock>75</stock>
            <manufacturer>
                <name>BrandY</name>
                <address>456 BrandY Ave, City, Country</address>
            </manufacturer>
            <features>
                <feature>Intel i7 Processor</feature>
                <feature>16GB RAM</feature>
                <feature>512GB SSD</feature>
            </features>
        </product>
        <product id="103">
            <name>Headphones</name>
            <category>Accessories</category>
            <price>199.99</price>
            <stock>200</stock>
            <manufacturer>
                <name>BrandZ</name>
                <address>789 BrandZ Blvd, City, Country</address>
            </manufacturer>
            <features>
                <feature>Noise Cancelling</feature>
                <feature>Bluetooth 5.0</feature>
                <feature>Over-ear design</feature>
            </features>
        </product>
    </products>
    
    
    json 데이터로 변환하여 출력한 결과: 
    {
        "products": {
            "product": [
                {
                    "@id": "101",
                    "name": "Smartphone",
                    "category": "Electronics",
                    "price": "599.99",
                    "stock": "150",
                    "manufacturer": {
                        "name": "BrandX",
                        "address": "123 BrandX St, City, Country"
                    },
                    "features": {
                        "feature": [
                            "5G Connectivity",
                            "6GB RAM",
                            "128GB Storage"
                        ]
                    }
                },
                {
                    "@id": "102",
                    "name": "Laptop",
                    "category": "Electronics",
                    "price": "999.99",
                    "stock": "75",
                    "manufacturer": {
                        "name": "BrandY",
                        "address": "456 BrandY Ave, City, Country"
                    },
                    "features": {
                        "feature": [
                            "Intel i7 Processor",
                            "16GB RAM",
                            "512GB SSD"
                        ]
                    }
                },
                {
                    "@id": "103",
                    "name": "Headphones",
                    "category": "Accessories",
                    "price": "199.99",
                    "stock": "200",
                    "manufacturer": {
                        "name": "BrandZ",
                        "address": "789 BrandZ Blvd, City, Country"
                    },
                    "features": {
                        "feature": [
                            "Noise Cancelling",
                            "Bluetooth 5.0",
                            "Over-ear design"
                        ]
                    }
                }
            ]
        }
    }

json to xml (json 데이터 xml로 변환)

1. 모듈 임포트

  • import json
    import xmltodict
  • json: JSON 데이터를 파싱하거나 JSON 문자열로 변환하기 위한 표준 라이브러리.
  • xmltodict: XML 데이터를 Python의 딕셔너리로 변환하거나, 딕셔너리를 XML로 변환하는 외부 라이브러리.

2. json 파일 열기 및 데이터 읽기

  • with open("../data/json_to_xml.json") as json_file:
        json_data = json_file.read()
  • open() 함수로 JSON 파일을 읽어옵니다.
  • read()를 사용하여 파일 내용을 문자열로 읽어옵니다.

3. json 문자열을 딕셔너리로 변환

  • json_dict = json.loads(json_data)
  • json 모듈의 loads()를 사용하여 JSON 문자열을 Python 딕셔너리로 변환합니다.
  • 이 변환은 JSON 데이터를 XML로 변환하기 위한 중간 단계입니다.

4. 딕셔너리를 xml로 변환

  • xml_data = xmltodict.unparse({"root": json_dict}, pretty=True)
    
    # xml의 엘리먼트 구조가 최상위 레벨의 엘리먼트가 하나라면 아래와 같이 사용할 수 있습니다.
    # xml_data = xmltodict.unparse(json.loads(json_data), pretty=True)
  • xmltodict모듈의 unparse() 함수로 딕셔너리를 xml 형식으로 변환합니다.
  • {"root": json_dict}: JSON 데이터를 XML로 변환할 때, 루트 요소를 지정해야 합니다.
    예를 들어, JSON 데이터가 루트 요소를 가지지 않는 경우, root라는 루트를 추가합니다.
  • pretty=True: 출력되는 XML을 읽기 쉽도록 포맷팅합니다.

5. xml 출력

  • json과 xml 출력
    더보기
    json 데이터 파일 읽어와서 출력한 결과: 
    {
      "products": [
        {
          "id": "101",
          "name": "Smartphone",
          "category": "Electronics",
          "price": 599.99,
          "stock": 150,
          "manufacturer": {
            "name": "BrandX",
            "address": "123 BrandX St, City, Country"
          },
          "features": [
            "5G Connectivity",
            "6GB RAM",
            "128GB Storage"
          ]
        },
        {
          "id": "102",
          "name": "Laptop",
          "category": "Electronics",
          "price": 999.99,
          "stock": 75,
          "manufacturer": {
            "name": "BrandY",
            "address": "456 BrandY Ave, City, Country"
          },
          "features": [
            "Intel i7 Processor",
            "16GB RAM",
            "512GB SSD"
          ]
        },
        {
          "id": "103",
          "name": "Headphones",
          "category": "Accessories",
          "price": 199.99,
          "stock": 200,
          "manufacturer": {
            "name": "BrandZ",
            "address": "789 BrandZ Blvd, City, Country"
          },
          "features": [
            "Noise Cancelling",
            "Bluetooth 5.0",
            "Over-ear design"
          ]
        }
      ]
    }
    
    
    xml 데이터로 변환하여 출력한 결과: 
    <?xml version="1.0" encoding="utf-8"?>
    <root>
    	<products>
    		<id>101</id>
    		<name>Smartphone</name>
    		<category>Electronics</category>
    		<price>599.99</price>
    		<stock>150</stock>
    		<manufacturer>
    			<name>BrandX</name>
    			<address>123 BrandX St, City, Country</address>
    		</manufacturer>
    		<features>5G Connectivity</features>
    		<features>6GB RAM</features>
    		<features>128GB Storage</features>
    	</products>
    	<products>
    		<id>102</id>
    		<name>Laptop</name>
    		<category>Electronics</category>
    		<price>999.99</price>
    		<stock>75</stock>
    		<manufacturer>
    			<name>BrandY</name>
    			<address>456 BrandY Ave, City, Country</address>
    		</manufacturer>
    		<features>Intel i7 Processor</features>
    		<features>16GB RAM</features>
    		<features>512GB SSD</features>
    	</products>
    	<products>
    		<id>103</id>
    		<name>Headphones</name>
    		<category>Accessories</category>
    		<price>199.99</price>
    		<stock>200</stock>
    		<manufacturer>
    			<name>BrandZ</name>
    			<address>789 BrandZ Blvd, City, Country</address>
    		</manufacturer>
    		<features>Noise Cancelling</features>
    		<features>Bluetooth 5.0</features>
    		<features>Over-ear design</features>
    	</products>
    </root>

최종 코드

  • xml to json 소스 코드
    더보기
    import json
    import xmltodict
    
    with open("../data/xml_to_json.xml", "r") as f:
        xml_data = f.read()
    
    print(f"\nxml 데이터 파일 읽어와서 출력한 결과: \n{xml_data}")
    
    json_data = json.dumps(xmltodict.parse(xml_data), indent=4)
    
    print(f"\njson 데이터로 변환하여 출력한 결과: \n{json_data}")
  • xml to json 결과
    더보기
    xml 데이터 파일 읽어와서 출력한 결과: 
    <?xml version="1.0" encoding="UTF-8"?>
    <products>
        <product id="101">
            <name>Smartphone</name>
            <category>Electronics</category>
            <price>599.99</price>
            <stock>150</stock>
            <manufacturer>
                <name>BrandX</name>
                <address>123 BrandX St, City, Country</address>
            </manufacturer>
            <features>
                <feature>5G Connectivity</feature>
                <feature>6GB RAM</feature>
                <feature>128GB Storage</feature>
            </features>
        </product>
        <product id="102">
            <name>Laptop</name>
            <category>Electronics</category>
            <price>999.99</price>
            <stock>75</stock>
            <manufacturer>
                <name>BrandY</name>
                <address>456 BrandY Ave, City, Country</address>
            </manufacturer>
            <features>
                <feature>Intel i7 Processor</feature>
                <feature>16GB RAM</feature>
                <feature>512GB SSD</feature>
            </features>
        </product>
        <product id="103">
            <name>Headphones</name>
            <category>Accessories</category>
            <price>199.99</price>
            <stock>200</stock>
            <manufacturer>
                <name>BrandZ</name>
                <address>789 BrandZ Blvd, City, Country</address>
            </manufacturer>
            <features>
                <feature>Noise Cancelling</feature>
                <feature>Bluetooth 5.0</feature>
                <feature>Over-ear design</feature>
            </features>
        </product>
    </products>
    
    
    json 데이터로 변환하여 출력한 결과: 
    {
        "products": {
            "product": [
                {
                    "@id": "101",
                    "name": "Smartphone",
                    "category": "Electronics",
                    "price": "599.99",
                    "stock": "150",
                    "manufacturer": {
                        "name": "BrandX",
                        "address": "123 BrandX St, City, Country"
                    },
                    "features": {
                        "feature": [
                            "5G Connectivity",
                            "6GB RAM",
                            "128GB Storage"
                        ]
                    }
                },
                {
                    "@id": "102",
                    "name": "Laptop",
                    "category": "Electronics",
                    "price": "999.99",
                    "stock": "75",
                    "manufacturer": {
                        "name": "BrandY",
                        "address": "456 BrandY Ave, City, Country"
                    },
                    "features": {
                        "feature": [
                            "Intel i7 Processor",
                            "16GB RAM",
                            "512GB SSD"
                        ]
                    }
                },
                {
                    "@id": "103",
                    "name": "Headphones",
                    "category": "Accessories",
                    "price": "199.99",
                    "stock": "200",
                    "manufacturer": {
                        "name": "BrandZ",
                        "address": "789 BrandZ Blvd, City, Country"
                    },
                    "features": {
                        "feature": [
                            "Noise Cancelling",
                            "Bluetooth 5.0",
                            "Over-ear design"
                        ]
                    }
                }
            ]
        }
    }
  • json to xml 소스 코드
    더보기
    import json
    import xmltodict
    
    with open("../data/json_to_xml.json") as json_file:
        json_data = json_file.read()
    
    print(f"\njson 데이터 파일 읽어와서 출력한 결과: \n{json_data}")
    
    json_dict = json.loads(json_data)
    
    xml_data = xmltodict.unparse({"root": json_dict}, pretty=True)
    
    # xml의 엘리먼트 구조가 최상위 레벨의 엘리먼트가 하나라면 아래와 같이 사용할 수 있습니다.
    # xml_data = xmltodict.unparse(json.loads(json_data), pretty=True)
    
    print(f"\nxml 데이터로 변환하여 출력한 결과: \n{xml_data}")
  • json to xml 결과
    더보기
    json 데이터 파일 읽어와서 출력한 결과: 
    {
      "products": [
        {
          "id": "101",
          "name": "Smartphone",
          "category": "Electronics",
          "price": 599.99,
          "stock": 150,
          "manufacturer": {
            "name": "BrandX",
            "address": "123 BrandX St, City, Country"
          },
          "features": [
            "5G Connectivity",
            "6GB RAM",
            "128GB Storage"
          ]
        },
        {
          "id": "102",
          "name": "Laptop",
          "category": "Electronics",
          "price": 999.99,
          "stock": 75,
          "manufacturer": {
            "name": "BrandY",
            "address": "456 BrandY Ave, City, Country"
          },
          "features": [
            "Intel i7 Processor",
            "16GB RAM",
            "512GB SSD"
          ]
        },
        {
          "id": "103",
          "name": "Headphones",
          "category": "Accessories",
          "price": 199.99,
          "stock": 200,
          "manufacturer": {
            "name": "BrandZ",
            "address": "789 BrandZ Blvd, City, Country"
          },
          "features": [
            "Noise Cancelling",
            "Bluetooth 5.0",
            "Over-ear design"
          ]
        }
      ]
    }
    
    
    xml 데이터로 변환하여 출력한 결과: 
    <?xml version="1.0" encoding="utf-8"?>
    <root>
    	<products>
    		<id>101</id>
    		<name>Smartphone</name>
    		<category>Electronics</category>
    		<price>599.99</price>
    		<stock>150</stock>
    		<manufacturer>
    			<name>BrandX</name>
    			<address>123 BrandX St, City, Country</address>
    		</manufacturer>
    		<features>5G Connectivity</features>
    		<features>6GB RAM</features>
    		<features>128GB Storage</features>
    	</products>
    	<products>
    		<id>102</id>
    		<name>Laptop</name>
    		<category>Electronics</category>
    		<price>999.99</price>
    		<stock>75</stock>
    		<manufacturer>
    			<name>BrandY</name>
    			<address>456 BrandY Ave, City, Country</address>
    		</manufacturer>
    		<features>Intel i7 Processor</features>
    		<features>16GB RAM</features>
    		<features>512GB SSD</features>
    	</products>
    	<products>
    		<id>103</id>
    		<name>Headphones</name>
    		<category>Accessories</category>
    		<price>199.99</price>
    		<stock>200</stock>
    		<manufacturer>
    			<name>BrandZ</name>
    			<address>789 BrandZ Blvd, City, Country</address>
    		</manufacturer>
    		<features>Noise Cancelling</features>
    		<features>Bluetooth 5.0</features>
    		<features>Over-ear design</features>
    	</products>
    </root>
  • 예시 데이터
    • XML
      더보기
      <?xml version="1.0" encoding="UTF-8"?>
      <products>
          <product id="101">
              <name>Smartphone</name>
              <category>Electronics</category>
              <price>599.99</price>
              <stock>150</stock>
              <manufacturer>
                  <name>BrandX</name>
                  <address>123 BrandX St, City, Country</address>
              </manufacturer>
              <features>
                  <feature>5G Connectivity</feature>
                  <feature>6GB RAM</feature>
                  <feature>128GB Storage</feature>
              </features>
          </product>
          <product id="102">
              <name>Laptop</name>
              <category>Electronics</category>
              <price>999.99</price>
              <stock>75</stock>
              <manufacturer>
                  <name>BrandY</name>
                  <address>456 BrandY Ave, City, Country</address>
              </manufacturer>
              <features>
                  <feature>Intel i7 Processor</feature>
                  <feature>16GB RAM</feature>
                  <feature>512GB SSD</feature>
              </features>
          </product>
          <product id="103">
              <name>Headphones</name>
              <category>Accessories</category>
              <price>199.99</price>
              <stock>200</stock>
              <manufacturer>
                  <name>BrandZ</name>
                  <address>789 BrandZ Blvd, City, Country</address>
              </manufacturer>
              <features>
                  <feature>Noise Cancelling</feature>
                  <feature>Bluetooth 5.0</feature>
                  <feature>Over-ear design</feature>
              </features>
          </product>
      </products>
    • JSON
      더보기
      {
        "products": [
          {
            "id": "101",
            "name": "Smartphone",
            "category": "Electronics",
            "price": 599.99,
            "stock": 150,
            "manufacturer": {
              "name": "BrandX",
              "address": "123 BrandX St, City, Country"
            },
            "features": [
              "5G Connectivity",
              "6GB RAM",
              "128GB Storage"
            ]
          },
          {
            "id": "102",
            "name": "Laptop",
            "category": "Electronics",
            "price": 999.99,
            "stock": 75,
            "manufacturer": {
              "name": "BrandY",
              "address": "456 BrandY Ave, City, Country"
            },
            "features": [
              "Intel i7 Processor",
              "16GB RAM",
              "512GB SSD"
            ]
          },
          {
            "id": "103",
            "name": "Headphones",
            "category": "Accessories",
            "price": 199.99,
            "stock": 200,
            "manufacturer": {
              "name": "BrandZ",
              "address": "789 BrandZ Blvd, City, Country"
            },
            "features": [
              "Noise Cancelling",
              "Bluetooth 5.0",
              "Over-ear design"
            ]
          }
        ]
      }