แปลง XML เป็น JSON
แปลง XML ให้เป็นรูปแบบ JSON
ป้อนข้อมูล XML
ผลลัพธ์ JSON
การแปลง XML เป็น JSON คืออะไร?
การแปลง XML เป็น JSON คือกระบวนการเปลี่ยนข้อมูลจาก Extensible Markup Language (XML) ให้เป็น JavaScript Object Notation (JSON) ทั้งสองรูปแบบแสดงข้อมูลที่มีโครงสร้างแบบลำดับชั้น แต่ใช้ไวยากรณ์และโมเดลข้อมูลที่แตกต่างกัน XML ใช้ opening tag และ closing tag พร้อม attribute ที่เป็นตัวเลือก ในขณะที่ JSON ใช้ key-value pair, array และประเภทข้อมูลพื้นฐาน การแปลง XML เป็น JSON ช่วยให้คุณทำงานกับข้อมูล XML ในสภาพแวดล้อมที่ JSON เป็นรูปแบบหลัก เช่น JavaScript runtime, REST API และฐานข้อมูล NoSQL
การแปลงนี้ไม่ได้เป็นแบบหนึ่งต่อหนึ่งเสมอไป XML มีโครงสร้างบางอย่างที่ไม่มีสิ่งเทียบเท่าใน JSON โดยตรง ได้แก่ attribute, mixed content (ข้อความที่สลับกับ child element), processing instruction, comment, CDATA section และการประกาศ namespace ไลบรารีต่างๆ จัดการโครงสร้างเหล่านี้ต่างกัน ซึ่งเป็นเหตุให้มีหลายแนวทางที่ใช้กัน แนวทางที่พบบ่อยที่สุดคือการเติม @ นำหน้าชื่อ attribute และวางเนื้อหาข้อความไว้ใน field #text เมื่อมี attribute อยู่ใน element เดียวกัน
การแปลง XML เป็น JSON เป็นขั้นตอนทั่วไปเมื่อย้ายระบบจาก SOAP ไปเป็น REST, ใช้งาน API องค์กรรุ่นเก่า หรือประมวลผลข้อมูลจากระบบราชการและการเงินที่กำหนดให้ใช้ XML แทนที่จะเขียนผู้ผลิตและผู้บริโภคข้อมูลใหม่พร้อมกัน ทีมงานแปลง XML payload ที่ชั้นขอบเขตและส่ง JSON ต่อไปยังส่วนปลายน้ำ AWS API Gateway, Apache Camel และ MuleSoft รองรับรูปแบบนี้ในตัว
<bookstore>
<book category="fiction">
<title lang="en">The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
<price>10.99</price>
</book>
<book category="non-fiction">
<title lang="en">Sapiens</title>
<author>Yuval Noah Harari</author>
<year>2011</year>
<price>14.99</price>
</book>
</bookstore>{
"bookstore": {
"book": [
{
"@category": "fiction",
"title": {
"@lang": "en",
"#text": "The Great Gatsby"
},
"author": "F. Scott Fitzgerald",
"year": "1925",
"price": "10.99"
},
{
"@category": "non-fiction",
"title": {
"@lang": "en",
"#text": "Sapiens"
},
"author": "Yuval Noah Harari",
"year": "2011",
"price": "14.99"
}
]
}
}ทำไมต้องใช้ตัวแปลง XML เป็น JSON ออนไลน์?
การเขียน script แปลงข้อมูลแบบครั้งเดียวใช้เวลานาน โดยเฉพาะเมื่อ XML มี attribute, namespace หรือ element ที่ซ้ำกันซึ่งต้องกลายเป็น JSON array ตัวแปลงบนเบราว์เซอร์ให้ผลลัพธ์ JSON ภายในไม่กี่วินาที เพื่อให้คุณตรวจสอบโครงสร้างและดำเนินการต่อได้ทันที
กรณีการใช้งานการแปลง XML เป็น JSON
ตารางอ้างอิงการแมป XML เป็น JSON
XML และ JSON มีโมเดลข้อมูลที่แตกต่างกัน ตารางด้านล่างแสดงการที่โครงสร้าง XML แต่ละแบบแมปไปยัง JSON ตามแนวทางที่พบบ่อยที่สุด (@ สำหรับ attribute, #text สำหรับข้อความที่อยู่คู่กับ attribute) โครงสร้างบางอย่าง เช่น mixed content และ comment ไม่มีการแทนที่มาตรฐานใน JSON
| โครงสร้าง XML | ตัวอย่าง XML | JSON ที่เทียบเท่า |
|---|---|---|
| Element | <name>text</name> | "name": "text" |
| Nested elements | <a><b>1</b></a> | "a": { "b": "1" } |
| Attributes | <el attr="v"/> | "el": { "@attr": "v" } |
| Text + attributes | <el a="1">text</el> | "el": { "@a": "1", "#text": "text" } |
| Repeated elements | <r><i>1</i><i>2</i></r> | "r": { "i": ["1", "2"] } |
| Mixed content | <p>A <b>B</b> C</p> | Varies by convention |
| CDATA | <![CDATA[raw]]> | "#cdata": "raw" or flattened |
| Namespaces | xmlns:prefix="uri" | Prefix preserved or stripped |
| Empty element | <el/> | "el": null or "" |
| Comments | <!-- note --> | Discarded (no JSON equivalent) |
เปรียบเทียบแนวทางการแปลง XML เป็น JSON
ไม่มีมาตรฐานเดียวที่กำหนดวิธีแมป XML ไปยัง JSON มีสามแนวทางที่ใช้กันอย่างแพร่หลาย แต่ละแบบมีข้อดีข้อเสียต่างกันในการจัดการ attribute, การตรวจจับ array และการรักษาข้อความ
ตัวอย่างโค้ด
ด้านล่างคือตัวอย่างที่ใช้งานได้จริงสำหรับการแปลง XML เป็น JSON ใน JavaScript, Python, Go และ command line แต่ละตัวอย่างรองรับ element ที่ซ้อนกันและ sibling tag ที่ซ้ำกัน
// Using the DOMParser API to walk XML and build a JSON object
function xmlToJson(xml) {
const parser = new DOMParser()
const doc = parser.parseFromString(xml, 'application/xml')
function nodeToObj(node) {
const obj = {}
// Handle attributes
if (node.attributes) {
for (const attr of node.attributes) {
obj['@' + attr.name] = attr.value
}
}
// Handle child nodes
for (const child of node.childNodes) {
if (child.nodeType === 3) { // text
const text = child.textContent.trim()
if (text) obj['#text'] = text
} else if (child.nodeType === 1) { // element
const key = child.nodeName
const val = nodeToObj(child)
if (obj[key]) {
if (!Array.isArray(obj[key])) obj[key] = [obj[key]]
obj[key].push(val)
} else {
obj[key] = val
}
}
}
// Simplify text-only nodes
const keys = Object.keys(obj)
if (keys.length === 1 && keys[0] === '#text') return obj['#text']
return obj
}
return nodeToObj(doc.documentElement)
}
const xml = '<user><name>Alice</name><role>admin</role></user>'
console.log(JSON.stringify(xmlToJson(xml), null, 2))
// → { "name": "Alice", "role": "admin" }import xmltodict
import json
xml = """
<user>
<name>Alice</name>
<roles>
<role>admin</role>
<role>editor</role>
</roles>
</user>
"""
# xmltodict converts XML to an OrderedDict
result = xmltodict.parse(xml)
print(json.dumps(result, indent=2))
# → {
# → "user": {
# → "name": "Alice",
# → "roles": { "role": ["admin", "editor"] }
# → }
# → }
# With the standard library (xml.etree.ElementTree)
import xml.etree.ElementTree as ET
def etree_to_dict(elem):
d = {}
if elem.attrib:
d.update({f"@{k}": v for k, v in elem.attrib.items()})
for child in elem:
child_data = etree_to_dict(child)
if child.tag in d:
if not isinstance(d[child.tag], list):
d[child.tag] = [d[child.tag]]
d[child.tag].append(child_data)
else:
d[child.tag] = child_data
if elem.text and elem.text.strip():
if d:
d["#text"] = elem.text.strip()
else:
return elem.text.strip()
return d
root = ET.fromstring(xml)
print(json.dumps(etree_to_dict(root), indent=2))package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"strings"
)
// For simple, known schemas — define a struct
type User struct {
XMLName xml.Name `xml:"user"`
Name string `xml:"name"`
Roles []string `xml:"roles>role"`
}
func main() {
data := `<user><name>Alice</name><roles><role>admin</role><role>editor</role></roles></user>`
var user User
xml.NewDecoder(strings.NewReader(data)).Decode(&user)
out, _ := json.MarshalIndent(user, "", " ")
fmt.Println(string(out))
// → { "Name": "Alice", "Roles": ["admin", "editor"] }
}# Using xq (part of yq, a jq wrapper for XML)
# Install: pip install yq OR brew install yq
echo '<user><name>Alice</name></user>' | xq .
# → { "user": { "name": "Alice" } }
# Using xmlstarlet + jq
xmlstarlet sel -t -v '//name' input.xml | jq -R '{ name: . }'
# Node.js one-liner with xml2js
echo '<a><b>1</b></a>' | node -e "
const {parseString} = require('xml2js');
let d=''; process.stdin.on('data',c=>d+=c);
process.stdin.on('end',()=>parseString(d,(e,r)=>console.log(JSON.stringify(r,null,2))))
"