Print JSON nested object in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To print JSON nested object in JavaScript, use for loop along with JSON.parse(). Following is the code −

Example

var details = [
   {
      "studentId": 101,
      "studentName": "John",
      "countryName": "US",
      "subjectDetails": "{\"0\":\"JavaScript\",\"1\":\"David\"}"
   },
   {
      "studentId": 102,
      "studentName": "Bob",
      "countryName": "UK",
      "subjectDetails": "{\"0\":\"Java\",\"1\":\"Carol\"}"
   },
   {
      "studentId": 103,
      "studentName": "Mike",
      "countryName": "AUS",
      "subjectDetails": "{\"0\":\"MongoDB\",\"1\":\"Adam\"}"
   }
]
for (const detailsObject of details) {
   const subjectDetailsObject =
   JSON.parse(detailsObject.subjectDetails);
   console.log(subjectDetailsObject[0]);
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo145.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo145.js
JavaScript
Java
MongoDB
raja
Published on 11-Sep-2020 08:19:44
Advertisements