Show List

JSON and XML parsing in JavaScript

JSON (JavaScript Object Notation) and XML (eXtensible Markup Language) are two popular formats for exchanging data between the client and server or between different applications.

Here's how to parse JSON and XML in JavaScript:

  1. JSON parsing: JSON is a lightweight data format that is easy to read and write, and it can be parsed by JavaScript using the JSON.parse method. The JSON.parse method takes a string of JSON-formatted data and returns a JavaScript object:
const jsonString = '{"name": "John", "age": 30}';
const person = JSON.parse(jsonString);
console.log(person.name); // outputs: "John"
  1. XML parsing: XML is a markup language that is commonly used for exchanging structured data. In JavaScript, XML data can be parsed using the DOMParser object, which creates a tree-like structure that can be manipulated using the Document Object Model (DOM) API:
const xmlString = '<person><name>John</name><age>30</age></person>';
const parser = new DOMParser();
const xml = parser.parseFromString(xmlString, "text/xml");
const name = xml.getElementsByTagName("name")[0].textContent;
console.log(name); // outputs: "John"
These are the basics of parsing JSON and XML in JavaScript. Depending on your use case, you may need to use additional techniques to extract data from the parsed data structures, but the JSON.parse method and the DOMParser object are a good starting point.

    Leave a Comment


  • captcha text