How to break down JSON into individual elements using JavaScript

{ "name": "Sophia", "age": "Unknown", "heroes": ["Batman", "Superman", "Wonder Woman"], "sidekicks": [ { "name": "Robin" }, { "name": "Flash Gordon" }, { "name": "Bucky Barnes" } ], "info": { "first": "James", "last": "Bond" } }

Desired Result:
name: Sophia

age: Unknown

heroes: Batman, Superman, Wonder Woman

sidekicks: name: Robin name: Flash Gordon name: Bucky Barnes

info: first: James last: Bond

Answer №1

JSON is a valid JavaScript object that allows you to easily store and retrieve data. For example, you can extract the name from JSON like this:var name = data.name; and here are the musketeers:

var musketeers = data.musketeers;
for (var i = 0; i < musketeers.length; i++) {
  console.log(musketeers[i]);
}

Answer №2

<html>
<head>
<script>
window.onload = function() {
var jsonValue={
                "name": "Chris",
                "age": "RIP",
                "musketeers": ["Athos", "Aramis", "Porthos", "Artagnan"],
                "stooges": [
                            { "name": "Moe" },
                            { "name": "Larry" },
                            { "name": "Curly" }
                            ],
                "name details": {
                "first": "Michael",
                "last": "Jackson"
                }
            };
if (!Array.prototype.inArray) {
    Array.prototype.inArray = function(element) {
        return this.indexOf(element) > -1;
    };
}                           
var key,key1,key2,innerdiv = '';
var array = ['0','1','2','3','4','5','6','7','8','9','10','11'];
for(key in jsonValue){
    if(jsonValue.hasOwnProperty(key)) {
        if(typeof(jsonValue[key])=='object'){
            innerdiv+="<div>"+key;
            for(key1 in jsonValue[key]){
                if(jsonValue[key].hasOwnProperty(key1)){
                    innerdiv+= "<p>";
                    if(typeof(jsonValue[key][key1]) =='object'){
                        for(key2 in jsonValue[key][key1]){
                            innerdiv+= key2 + " <input type='text' name='"+key2+"' value='"+jsonValue[key][key1][key2]+"'></p>";
                        }
                    }
                    else{
                        if(array.inArray(key1)){
                            innerdiv+= " <input type='text' name='"+key1+"' value='"+jsonValue[key][key1]+"'></p>";
                        }
                        else{
                            innerdiv+= key1 + " <input type='text' name='"+key1+"' value='"+jsonValue[key][key1]+"'></p>";
                        }
                    }
                }
            }
            innerdiv+="</div>";
        }
        else{
            innerdiv+= "<p>"+key+" <input type='text' name='"+key+"' value='"+jsonValue[key]+"'></p>";
        }
    }

} 
document.getElementById("htmlContent").innerHTML = innerdiv;
};

</script>
</head>

<form name="" action="" method="">
        <div id="htmlContent"></div>
        <input type="submit" name="submit" value="submit">
</form>
</html>

Answer №3

Give this a shot

Implement the JSON.Parse() function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring date range options in Highcharts for viewing data from a specific selected date

Using HTML, JS, and Controller public function graph(Request $request) { $statistics = DiraStatistics::where('date_access',$request->date)->get(); $question_asked_sum = $statistics->sum('question_asked'); $low_ ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

Waiting for Angular's For loop to complete

Recently, I encountered a situation where I needed to format the parameters and submit them to an API using some code. The code involved iterating through performance criteria, performance indicators, and target details to create new objects and push them ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Deriving worth from a JSON object

My JSON data structure has the following format: .... "location" : { "lat" : 37.42140090, "lng" : -122.08537010 }, .... I am having trouble accessing the lat and lng values. Any suggestions on how to do this? Cu ...

Combining NodeJS and ExpressJS to deliver a unified JavaScript file when in production mode

Currently, I am managing multiple individual JS files in the following way: <script defer src="/js/libs/jquery.min.js"></script> <script defer src="/js/libs/plugins.js"></script> <!-- application core --> <script defer sr ...

Encountering a problem when utilizing the each loop within an ajax request

While attempting to iterate through a each loop within an Ajax call, I encounter the following error: TypeError: invalid 'in' operand e Here is my Ajax call code snippet: $.ajax({ type: "POST", url: "/admin/counselormanagem ...

Embarking on a new Android project ahead!

Starting a new project on Android focused on car sales. Firstly, which libraries should be used for the interface? The main functionalities needed are: 1) Displaying images in grid blocks covering the entire screen. 2) Implementing image zooming feature. ...

Can we establish communication between the backend and frontend in React JS by utilizing localstorage?

Trying to implement affiliate functionality on my eCommerce platform. The idea is that users who generate links will receive a commission if someone makes a purchase through those links. However, the challenge I'm facing is that I can't store the ...

Pass KeyEventArgs object to JavaScript function

Is it possible to pass keydown events as parameters to a JavaScript function in Silverlight4? ...

Fetching content-type in React code locally executed

I am a beginner in front end development and I need help with setting the "application/json" content-type and gzip content-encoding in the fetch call for my locally run React code. Can anyone provide guidance on this? const data = await fetch(url, { ...

Can you explain the distinction between postMessage() and dispatchEvent() in relation to the origin policy?

Here is some code that I wrote. I tried setting the MessageEvent's origin to *, but I'm still getting an error in the console saying "Blocked a frame with origin "AAAA" from accessing a frame with origin "BBBB". Protocols, domains, and ports must ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

Is Angular automatically assigned to `window.angular` on a global level when it is loaded as a CommonJS module?

When I import Angular 1.4 in my Webpack build entry point module as a CommonJS module using var angular = require("angular");, it somehow ends up being accessible in the global namespace of the browser (as window.angular). Upon examining the source code o ...

Are you searching for the origin of a dynamic dropdown widget or database?

Currently, I am browsing through and I have a query regarding accessing all available classes/options for the courses in a semester. There is a class locator on the top left of the page with a dynamic drop-down menu. Can anyone suggest how I can access ...

Code error: JSON unexpected token "&" encountered

When utilizing the $http.get() method for a GET request, the response is in JSON format, but some characters are HTML encoded. For example, the double quote " is encoded as &quot;. { &quot;description&quot;:&quot;invalid&quot;, ...

Provide users with the option to select a specific destination for saving their file

In the midst of my spring MVC project, I find myself in need of implementing a file path chooser for users. The goal is to allow users to select a specific location where they can save their files, such as C:\testlocation\sublocation... Despite r ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

JavaScript - issue with event relatedTarget not functioning properly when using onClick

I encountered an issue while using event.relatedTarget for onClick events, as it gives an error, but surprisingly works fine for onMouseout. Below is the code snippet causing the problem: <html> <head> <style type="text/css"> ...