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

What is the significance of Fawn's statement, "Invalid Condition"?

Despite following the instructions and initiating Fawn as stated in the document, I'm still encountering an error message that says Invalid Condition. Can anyone help me identify what is causing this issue? Thank you to all the helpers. await new Fawn ...

What is the best way to structure my POST data when conducting tests on an express API endpoint?

I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack. Currently, I am trying to test a POST API endpoint that is built using express. The node server is up ...

Converting a date from PHP to JavaScript

My PHP code generates the following date: <?php date_default_timezone_set('Europe/London'); echo date('D M d Y H:i:s O'); ?> Additionally, I have a JavaScript/jQuery script that displays this date on the website: setInterval( ...

Displaying image titles when the source image cannot be located with the help of JavaScript or jQuery

I am currently facing an issue where I need to display the image title when the image is broken or cannot be found in the specified path. At the moment, I only have the options to either hide the image completely or replace it with a default image. $(&apo ...

Cached images do not trigger the OnLoad event

Is there a way to monitor the load event of my images? Here's my current approach. export const Picture: FC<PictureProps> = ({ src, imgCls, picCls, lazy, alt: initialAlt, onLoad, onClick, style }) => { const alt = useMemo(() => initial ...

Issue with the scope causing global variable not to update when button is pressed

I am facing an issue with a declared variable and jQuery code that is supposed to store a form's value as the value of that variable when a button is clicked, and then execute a function. var verb = ""; $( "#submit" ).click(function() { verb = $(& ...

Question: How come I am receiving the error message "TypeError: Cannot read property 'toLowerCase' of undefined" in React JS?

Hi there, I'm new to this and trying to create a search filter. However, I keep encountering an error that says: Error: Cannot read property 'toLowerCase' of undefined It seems like the issue is related to the data type used with toLowerCa ...

Shifting JSON Arrays in JavaScript - Changing Order with Ease

Consider the following JSON data: [ { "name": "Lily", "value": 50 }, { "name": "Sophia", "value": 500 }, { "name": "Ethan", "value": 75 } ] I am looking to verify and organize it in ...

Currently, I am encountering a problem as I attempt to iterate through a dynamic table

I have a table containing various elements. An example row is Jack Smith with multiple rows like this: col1 col2 col3 col4 col5 col6 col7 col8 jack smith 23 Y Y error error_code error_desc The table is ...

Why am I not seeing my views when trying to export them from a file in my routes folder?

I've been tinkering around with basic routing in ExpressJS and up to this point, I have implemented two routes: app.get('/', function(req,res) { res.render('index'); }); app.get('/pics', function(req,res) { res.rend ...

Is it possible to merge a variable within single quotes in XPath?

Currently working with nodeJS and experimenting with the following code snippet: for (let i = 1; i <= elSize; i++) { try { let DeviceName = await driver .findElement(By.xpath("//span[@class='a-size-medium a-color-base a-text-normal ...

Utilizing DOMPDF in conjunction with jQuery to generate PDF files

Apologies for any language errors in my writing. I am attempting to generate a PDF using a portion of HTML, utilizing jQuery, Ajax, and DomPDF. On the server side, I am using the following code: require_once './dompdf/autoload.inc.php'; if(!em ...

Is there a way to temporarily toggle classes with jQuery?

Incorporating ZeroClipboard, I have implemented the following code to alter the text and class of my 'copy to clipboard button' by modifying the innerHTML. Upon clicking, this triggers a smooth class transition animation. client.on( "complete", ...

Techniques for manipulating multiple circles with JavaScript

After creating a series of circles with d3, I successfully implemented the functionality to drag individual circles and track their positions. var width= 800; var height=600; svg= d3.select("body").select(".div1").append("svg") ...

Guide on implementing two submission options in an HTML form using JavaScript

Currently, I am working on a form that includes two buttons for saving inputted data to different locations. However, I am facing an issue with the functionality of the form when it comes to submitting the data. Since only one submit function can be activa ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

Deactivate any days occurring prior to or following the specified dates

I need assistance restricting the user to choose dates within a specific range using react day picker. Dates outside this range should be disabled to prevent selection. Below is my DateRange component that receives date values as strings like 2022-07-15 th ...

There seems to be a caching issue in ReactJS and Spring Data Rest that could be causing problems with

Encountering an unusual caching problem here. Just recently wiped out my database. While adding new users to the system, an old user mysteriously reappeared. This user has not been recreated and is not in the current database whatsoever. I'm at a lo ...

What is the best way to include variable child directives within a parent directive in AngularJS?

Exploring a New Angular Challenge In the current project I am engaged in, I am faced with a unique problem that requires an 'angular way' solution. Despite my best efforts, I seem to be hitting a roadblock every time I attempt to solve it. The ...

Leveraging URL parameters within node.js and Express

Having no prior experience with node, I decided to delve into the Express project in VS2019. My goal was to create master/detail pages with a MongoDB data source. In my pursuit, I configured three routes in /routes/index.js. //The following route works as ...