Using JavaScript to extract data from JSON with differing value types

Struggling to format a String by parsing a JSON object. Here's an example of the data I'm working with:

{
    "age": 35,
    "name": "",
    "time": {
        "24hr": true,
        "12hr": false
    }
}

The desired output should be:

age - 35
name
time - 24hr:true, 12hr:false

The problem lies in handling keys with different value types (integer, empty string, and object).

Seeking advice on the best method to achieve this formatting goal.

Currently able to loop through and print out keys, but experiencing issues with displaying values accurately.

Appreciate any help!

Answer №1

No major challenges are expected with most value types.

Check out this basic illustration that demonstrates a method without resorting to recursion:

var o = {
    "age": 35,
    "name": "",
    "time": {
        "24hr": true,
        "12hr": false
    }
}, 
s = [],
x = [],
v, k, p;

for (k in o) {
   if (typeof (v = o[k]) === 'object') {
       s.push(k + ' - ');
       x.length = 0;
       for (p in v) {
           x.push(p + ':' + v[p]);
       }
       s.push(x.join(', ') + '\n');
   } else {
       s.push(k + ' - ' + v + '\n');
   }
}

console.log(s.join(''));

You could apply a similar technique to dynamically generate an HTML structure rather than crafting a string.

Answer №2

Check out this jsFiddle Demo

HTML Code Snippet

<div>
    <span>age - </span>
    <span id='age'></span>
</div>
<div>
    <span>name - </span>
    <span id='name'></span>
</div>
<div>
    <span>time - 24hr: </span>
    <span id='24hr'></span>
    <span>, 12hr: </span>
    <span id='12hr'></span>
</div>

JavaScript Function

window.onload=function(){
    var json = '{"age": 35,"name": "","time": {"24hr": true,"12hr": false}}';
    var jObject = eval("("+json+")");
    document.getElementById("age").innerHTML = jObject.age;
    document.getElementById("name").innerHTML = jObject.name;
    document.getElementById("24hr").innerHTML = jObject.time["24hr"];
    document.getElementById("12hr").innerHTML = jObject.time["12hr"];
};

PLEASE NOTE: It is highly recommended to use a JSON parser instead of eval.

Recommended Libraries:

  1. JSON2 Library
  2. JSON.parse (limited support)

Example using JSON2 Library

window.onload = function () {
    var json = '{"age": 35,"name": "","time": {"24hr": true,"12hr": false}}';
    var jObject = JSON.parse(json);
    document.getElementById("age").innerHTML = jObject.age;
    document.getElementById("name").innerHTML = jObject.name;
    document.getElementById("24hr").innerHTML = jObject.time["24hr"];
    document.getElementById("12hr").innerHTML = jObject.time["12hr"];
};

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

Displaying a Div element containing dynamically calculated values based on selected options in Angular

As a newcomer to Angular, I decided to challenge myself by building a simple app. Currently, my select options only display the keys of a data object. What I really want to achieve is to show a value beneath the second select box for each team, which displ ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

Unable to locate module specifier three

Currently, I am working on Three.js in three different modules and using Express as the backend server. In my console, I keep encountering the error: "Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with eith ...

Refresh the dropdownlist in the ViewBag using AJAX

I am currently developing a cascaded dropdown list where data is passed using dataview. Controller: public ActionResult Index() { ViewBag.States = new SelectList(db.PLStates, "PLStateID", "PLStateName"); ViewBag.Cities = new SelectList(db.PLCitys ...

Ship using mail delivery with restangular

Having trouble sending a JSON via post with Restangular as it's not returning anything: Code: $scope.userPost = { title: 'foo', body: 'bar', userId: 1 } $scope.registerUser=function(){ $sc ...

Chrome Extension to Emphasize Every Word

As a novice, I am embarking on the journey of creating my own chrome extension. The idea is to design a popup.html file that showcases a "highlight" button. The functionality would involve clicking this button to highlight all words on the page. Here&apos ...

The Yeoman AngularFire user service encountered an unexpected issue with the userProvider provider, causing it to

I'm facing an issue when trying to inject a service into a controller in a Yeoman AngularFire application. Below is the controller (generated by Yeoman) where I am attempting to inject user: angular.module('myYoApp') .controller(&apo ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Why is npm attempting to compile a previous version of my code?

Being a complete newbie to npm and node.js, I hope you can bear with me if I'm lacking in providing the right details. I am working on developing a plugin for a website that utilizes an out-of-the-box framework within npm. Initially, everything was ru ...

Which Eslint rule is responsible for identifying incorrect or undefined methods in React components?

I recently came across a discussion on Stack Overflow regarding setting up an ESLint rule for unused class methods in a React component. The post mentioned that this might not be achievable without the use of third-party packages. However, I was wonderin ...

Is there a way to envelop each express js request within a domain or trycatch block?

Is it feasible to encompass each incoming request in express.js with a domain or trycatch for error handling? You can find more information about trycatch here. I am attempting to establish a comprehensive error handling mechanism (since the express error ...

The automated linting process through npm script did not meet the desired expectations

I need help setting up a script that will automatically fix all files in my Vue project like this: "lint": "eslint --fix vue/**/*.vue && eslint --fix vue/**/*.js" The goal is to automatically lint all .vue and .js files within the project. Unfor ...

Tips for transferring the content of a variable to a handlebars block

Currently, I am grappling with HTML code that involves handlebars templates to store internal variables. While I may not be an expert in handlebars, I am trying my best to navigate through it. The crux of my issue lies in the need to access a lengthy list ...

Customized HTML Template Tag

While I understand that using custom html tags is generally frowned upon for various reasons, I have a specific scenario that I believe might warrant the use of a custom html tag. I hope to either be proven wrong or discover a better way of achieving my ob ...

Altering the way in which URL parameters are attached to links depending on the destination

Our company utilizes Unbounce to create PPC landing pages on a subdomain, which then direct users back to our main website. We have implemented code that appends the AdWords gclid variable to outgoing links: $(document).ready(function() {var params = win ...

Quickblox: No response from recipient's device on message status

Our messaging system uses the latest Jars/SDK for read/delivered statuses and web-service to send messages across Android, iOS, and Web platforms. I set the message as SetMarkable(True), but it is received as false on both ends. If I reload all messages f ...

I must pause for a specified period before initializing the subsequent component in React Native

Due to restrictions on my API key, I can only make one request every 5 seconds. Therefore, I need to wait for 5 seconds before making another request for NearbyJobs (with the first request being made for PopularJobs). <ScrollView showsVerticalScrollIndi ...

Leveraging the power of Google Closure Templates alongside the versatility of

We are embarking on developing an application using JavaScript and HTML5 that will utilize a rest API to access server resources, leveraging the power and convenience of jQuery which our development team is already proficient in. Our goal is to make this a ...

Organize the rows of the table based on two variables

Currently, I am tackling the challenge of dynamically sorting a table using javascript/jQuery. The table rows come with two crucial attributes: deadline (measured in Unix timestamp) status (either 1 or 2) The primary requirement is to sort the table by s ...

Encountered the issue: "Received the error message 'MongooseServerSelectionError: Server selection timed out after 30000 ms.'"

I encountered the following error: MongooseServerSelectionError: Server selection timed out after 30000 ms while working with MongoDB Atlas. I attempted changing the useUnifiedTopology setting to false, which prevented my application from crashing. However ...