Tips for modifying a JSON array post-encoding

Is there a way to update a JSON array that has already been encoded as JSON?

I am interested in modifying the following JSON array :

{"Status":"OK","Message":"API Call worked","Result":[{"interval":"2014-11-30",
"leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}

To transform it into this

{"Result":"OK","Records":[{"interval":"2014-11-30",
"leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}

How can I make changes to the array using JavaScript?

Answer №1

If you are looking to achieve this using JavaScript, one way is to create a new JavaScript object, referred to as newJSON in the example below, and manually copy over the properties from your existing JSON object (referred to as oldJSON):

var oldJSON = ...,
    newJSON = {};

newJSON.Result = oldJSON.Status;
newJSON.Records = oldJSON.Result;

The variable newJSON now holds the desired format of the data as a JavaScript object. By calling JSON.stringify on this object, you can see the stringified result. Click on Run code snippet below to view the alerted result.

var oldJSON = {"Status":"OK","Message":"API Call worked","Result":[{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},{"interval":"2014-11-30","leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]},
    newJSON = {};

newJSON.Result = oldJSON.Status;
newJSON.Records = oldJSON.Result;

alert(JSON.stringify(newJSON));

Answer №2

obj['Data']=obj.Result;
obj['Result']=obj.Status;

If you're okay with additional keys in the JSON, there's no need to remove them. However, if you prefer to remove them, you can refer to these questions here. Hopefully this information is helpful.

Answer №3

Here is a suggestion for adjusting the JSON keys:

You may want to consider modifying or deleting certain keys in the JSON object. Here's an example of how you could do this:

var jsonData = '
    {"Status":"OK",
     "Message":"API Call worked",
     "Result": [
        {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
        {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
        {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}]}
';

var objData = JSON.parse(jsonData);

objData.Records = objData.Result;
delete objData.Result;

objData.Result = objData.Status;
delete objData.Status;

delete objData.Message;

jsonData = JSON.stringify([objData]);

After these adjustments, the JSON object would look like this:

{"Records": [
     {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"NEW","appointment":0},
     {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL1","appointment":0},
     {"interval":"2014-11-30", "leads":0,"name":"CarEnquiry","status":"CALL2","appointment":0}
   ],
 "Result":"OK"
}

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 best way to transfer JSON data from one file to another file in JSON format?

A unique json file is at my disposal, revealing an intriguing look: *{ "_id": "5f70aa5c04d7a034fc19e8969b000599", "contributors": null, "coordinates": null, "created_at": "Wed May 06 09:32:46 +0000 2020", ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

Issue encountered while trying to access Contentful's API using the getEntry() helper: promise for retrieved entry does not return any content

Introduction A few days ago, I reached out for assistance regarding the Contentful API and a javascript query issue on Stack Overflow. Since then, I have been grappling with understanding how to effectively utilize this API in conjunction with NextJS. Th ...

Error 404: "Headers already sent to the client cannot be modified"

I'm currently developing a Node/Express application and I want it to display a 404 page if a promise function doesn't resolve. This is my approach: app.get("/projects", t("projects", function(req, res) { res.header("Cache-Control", "private ...

Open the iframe link in the main window

As a newcomer to this platform, I am trying to figure out how to make a link open in the parent page when clicking a button within an iframe. Currently, my code opens the link in a new window. <html> <body> <form> <div class ...

Angular version 4 is used to retrieve deeply nested JSON data

How do I extract data from a nested JSON file? Here is an example of the JSON structure: { "user1": { "name": "john", "surname": "johnsson" }, "user2": { "name": "Jacob", "surname": "Jacobsson" } } I want t ...

Can a faulty image be cached?

Is there a way to ensure that the browser caches invalid or broken images so that when they are re-fetched, the loading time is immediate? I am particularly interested in two scenarios: 1) The first scenario involves trying to load an image from a URL co ...

The values on the x-axis do not appear to be showing up in Fusion Charts when viewing a heat map

I've incorporated the angular-fusion charts directive into my application and successfully created a heat map chart following an example. However, I'm encountering an issue where the values of the x-axis are not displaying in my application. I&ap ...

Does React router encounter issues when paired with react hooks?

Currently, I am developing a react application that consists of 3 main components: AdminShopRoutes, AdminShop, and Products. The AdminShopRoutes Component: const AdminShopRoutes = () => { return ( <Router> <Header> ...

Is there a way to automatically navigate to the accounting dashboard once the extract import is complete?

In the Odoo accounting module, you have the option to import bank statements. After the import is completed, it automatically takes you to the reconciliation view, but I am looking to redirect it to the accounting dashboard. Upon further inspection, I dis ...

Quick shorthand if statement that will constantly return true

I am dealing with a dropdown menu that displays different groups. Each group has a property (boolean) indicating whether the owner is a user or another group. If the group's owner is a user, I obtain the ownerID of the group and compare it with an ar ...

Close modal using jQuery when the submit button is clicked

My bootstrap modal is quite large. <div className="add-date"> <div className="modal" id="eventSelectedModal" tabIndex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true"> <div className="modal-dialog" role="do ...

A method to display the value inside the public void testDistanceBetween_AD - Printing the value in public void test

I am presenting my source code for this issue because I am facing difficulty in printing the values of a, b, and c within the TrainsTest class. The following methods are causing issues when trying to print the value out: public void testDistanceBetween_AB ...

Sorting strings in C using an array of pointers

Currently, I am working on my lab assignment that involves working with strings, arrays, and pointers. The task at hand is to "sort 5 string words stored in an array of pointers." I have put in a lot of effort and even searched for solutions to this probl ...

Does Java have an array object with a predetermined length?

I am seeking a solution to store multiple data types within a single fixed-length collection in order to access elements by index. Can someone advise on the most effective approach to achieve this? Thank you! EDIT: Would the following code snippet be vali ...

Using Paper.js to access and manipulate document.body.style.opacity within a paperscript

My website is essentially one large canvas image. Currently, the body fades in when loaded using this code: <body onLoad="document.body.style.opacity='1'"> However, I want to initiate this fade within my paperscript because sometimes the ...

The specified module cannot be located in the babel.config.json file

Recently, I've started using Babel by following the installation guide provided here https://babeljs.io/setup#installation The guide mentions that plugins need to be installed for Babel to function properly: Out of the box, Babel doesn't perf ...

Is it possible to utilize ko.observableArray in the form of a map?

Can an ko.observableArray be used as a map or dictionary? For instance: var arr = ko.observableArray(); arr.push('key', { '.. Some object as value ..' }); And then retrieve the value using the key: var value = arr['key']; ...

Displaying the parsed values from a JSON file and populating a list with the help of a one

package com.pack.indium.mismobile.activities; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ActionBar; import android.app.Activity; import android.app.ProgressDialog; import android.content.Inten ...

Tips for initiating a jQuery form submission

At this moment, the form is being submitted using the default URL. I would like it to utilize the form submit event in my JavaScript code so that it can pass the .ajaxSubmit() options. Below is the corresponding JavaScript code: $('#selectedFile&a ...