What steps do I need to take to modify a JSON parser?

I need assistance in converting a parser to JSON for a new server response.

Previous server response:

{"names":[{"name":"Oleg","act":0,"total":0},{"name":"Vitya","act":2,"total":2}]}

Existing parser:

names = appData.filter( function(x) { return skipped.indexOf(x) < 0; })
        get("https://serv.io/set?" + names.join("|")).then(function(data) {
          result = JSON.parse(data)["names"]
          for (var i = 0; i < result.length; i++) {
            name = result[i]["name"]
            act = result[i]["act"]
            total = result[i]["total"]
          }

New server response:

{"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}

In the updated response, there is no array and the object's name matches the name. I am seeking guidance on modifying the old parser for the new server response. Your help would be greatly appreciated!

Answer №1

To extract keys from an object, you can utilize the for...in loop. Another handy technique for working with this type of data is destructuring assignment.

const result = {"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}

for (const key in result) {
  const name = key
  const {act, total} = result[key]
  
  console.log(name, act, total)
}

It's important to note that when using for..in loop, the order of elements in the extracted JSON may not be preserved.

for...in does not guarantee the order of returned indexes.

(quoted from the for..in reference mentioned above.)

If maintaining the element order is critical for your system, you should consider utilizing a different JSON parser instead of the default JSON.parse() method.

Answer №2

Emulating the response server:

// Simulated server response
const data = JSON.stringify({"Anna":{"act":1,"total":5},"Elena":{"act":3,"total":8}})

// Assuming that you have already declared the necessary variables
let name;
let act;
let total;

// Parsing the JSON and working with it
const result = JSON.parse(data)

// Storing this result in a variable to avoid using Object.entries repeatedly.
const names = Object.entries(result);

// Creating a new loop for processing the data
for (var i = 0; i < names.length; i++) {
  name = names[i][0];
  act = names[i][1].act;
  total = names[i][1].total
  console.log(name, act, total);
}

The following will be the output on each iteration of the loop:

Anna 1 5
Elena 3 8

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

Tips for converting a CSV file into a map using Jackson's deserialization techniques

Looking to deserialize a CSV file into an object using Jackson. class Foo { String x, y, z; } I've successfully deserialized it into a List<Foo>, but I'm curious if there's a way to deserialize it into a Map<String, Foo> in ...

Retrieve a single element from an array using async waterfall in Node.js and MongoDB

I am working on creating a child and parent category menu using nodejs, mongodb, and angularjs. I am encountering an issue where the array being returned in the callback only contains a single record, despite having multiple data entries. I am unsure of wh ...

Troubleshooting: Page Unable to Import/Execute Linked JavaScript on WebStorm with Node.js Backend

I've been following W3School's jQuery tutorial, but I'm encountering some issues with importing scripts to an HTML document hosted on a Node server in WebStorm. I have properly installed and enabled the jQuery libraries under Preferences &g ...

The issue arises when the AngularJS function is unable to properly update due to a

When I create a dropdown menu using ng-repeat, my function fails if the JSON data is in string format, but works fine with integers. HERE IS AN EXAMPLE As you can observe, the chart uploads successfully with the year selected from the dropdown as an inte ...

Using JavaScript, you can employ the .split() and .replace() methods on a string value to accurately extract the specific

I'm currently attempting to extract hashtags from a text string by splitting it and removing unwanted HTML tags. Despite my efforts, I haven't been able to achieve the desired outcome. I am seeking guidance on where I might be going wrong. Here ...

Switching the body's background image dynamically using javascript

I'm attempting to switch up the background image using JavaScript. Here's how I've defined the background: body { background: black; overflow-x: hidden; overflow-y: hidden; } body:before { overflow-x: hidden; overflow ...

What is the method to modify the hover background color and click background color for a dropdown item using Bootstrap Vue?

Hovering over the dropdown will change its background color to a light gray. The code below shows the dropdown in a navbar. <b-nav-item-dropdown text="TOOLS" right> <b-dropdown-item href="#" class="dropdown-mine">1</b-dropdown-item> ...

Obtain JSON information using an underscore template

As someone fairly new to using Backbone and Underscore, and web development in general, I am seeking guidance on how to retrieve individual model data on-click from a template format in order to populate a pop-up modal. Any advice or direction would be gre ...

When utilizing the React onclick function, it generates an increase in state values rather than modifying

I'm currently working on a function that changes the state property, "changedMarkup", when a button is clicked. Initialization constructor() { super(); this.state = { value: 0, changedMarkup: 0 }; } Render Function render() ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

What is causing the Angular-UI TypeAhead code to display all items instead of filtered items?

I have been experimenting with the angular-ui typeahead directive to create a filtered input box that only shows items based on what has been typed. However, my current code is displaying all the items instead of just the filtered ones. If you'd like ...

Tips for ensuring all data is downloaded in Firebase (Firestore) Storage before proceeding?

I am currently developing a light dashboard in Vue that connects to Firestore and Storage. As someone who is not an expert, I have encountered a roadblock in what should be a simple task. The issue lies with a function that is meant to retrieve all URLs ba ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

Sending an array of properties to a child component

I am attempting to pass an array of objects from a parent component to a child component as a prop, then iterate over it using map and display the items in the child component. However, when I try to use map on the array nothing is happening, even though ...

Implement the use of HTML buttons to dynamically change the source attribute of an image using

I am in the process of creating a webpage with 25 different images that will be displayed one at a time. Each image represents unique combinations from two sets of items: (ant, blueberry, ladybug, marshmallow, mushroom) and (blimp, truck, moon, ocean, redw ...

I incorporated JSON into my codeigniter project as follows

Here is the code snippet $.post("color/color1", {color : e}, function(data) { var out=data + "<a class='one'>total</a>"; console.log(out); output.html(out); } This is the resulting content as displayed by the browser ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

Reverse lookup and deletion using Mongoose

Currently, I am attempting to perform a health check on the references within one of my collections. The goal is to verify if objects being referenced still exist, and if not, remove that particular _id from the array. Despite my efforts, I have not come ...