JSON vs XML
JSON 和 XML 均可用于从 web 服务器接收数据。
下面的 JSON 和 XML 实例都定义了雇员对象,包含了由 3 个雇员构成的数组:
JSON 实例
{"employees":[ { "firstName":"Bill", "lastName":"Gates" }, { "firstName":"Steve", "lastName":"Jobs" }, { "firstName":"Elon", "lastName":"Musk" } }]
XML 实例
<employees> <employee> <firstName>Bill</firstName> <lastName>Gates</lastName> </employee> <employee> <firstName>Steve</firstName> <lastName>Jobs</lastName> </employee> <employee> <firstName>Elon</firstName> <lastName>Musk</lastName> </employee> </employees>
JSON is similar to XML because:
- Both JSON and XML are 'self-descriptive' (human-readable)
- Both JSON and XML are hierarchical (values contain values)
- Both JSON and XML can be parsed and used by a large number of programming languages
- Both JSON and XML can be read by XMLHttpRequest
The differences between JSON and XML are:
- JSON does not use tags
- JSON is shorter
- JSON has faster read/write speed
- JSON can use arrays
The biggest difference is:
XML must be parsed using an XML parser. JSON, on the other hand, can be parsed using standard JavaScript functions.
Why is JSON better than XML?
- XML is more difficult to parse than JSON.
- JSON is parsed into a JavaScript object that can be used.
For AJAX applications, JSON is faster and easier to use than XML:
Use XML
- Read XML Document
- Use XML DOM to traverse the document
- Extract the value stored in the variable
Use JSON
- Read JSON String
- JSON.Parse JSON String