Currently, I am converting an object to a string, such as {'foo': 'bar'}
What is the process for converting the string back into an object?
Currently, I am converting an object to a string, such as {'foo': 'bar'}
What is the process for converting the string back into an object?
To properly handle your valid JSON string, you must utilize the JSON.parse()
method.
var data = '{"name":"John", "age":30, "city":"New York"}';
try {
var parsedData = JSON.parse(data); // this is how you parse a string into JSON
document.body.innerHTML += parsedData.name;
} catch (error) {
console.error(error);
}
JSON.stringify
and JSON.parse
are two complementary functions that work together in handling JSON data.
When using `JSON.stringify` and `JSON.parse`, they are often seen as opposites, with the following pattern typically yielding two objects that are "the same":
var obj = ...;
var json = JSON.stringify(obj);
var obj2 = JSON.parse(json);
Although this method usually works well for simple objects, there are some limitations to be mindful of.
This helper function, jsonrepack
, can help illustrate these limitations:
function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
Only own properties are retained, losing prototypes:
var MyClass = function() { this.foo="foo"; }
MyClass.prototype = { bar:"bar" }
var o = new MyClass();
var oo = jsonrepack(o);
console.log(oo.bar); // undefined
console.log( oo instanceof MyClass ); // false
Identity is lost:
var o = {};
var oo = jsonrepack(o);
console.log( o === oo ); // false
Functions do not survive:
jsonrepack( { f:function(){} } ); // Returns {}
Date objects become strings:
jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
Undefined values do not survive:
var v = { x:undefined }
console.log("x" in v); // true
console.log("x" in jsonrepack(v)); // false
Objects with a toJSON
function may behave unexpectedly.
x = { f:"foo", toJSON:function(){ return "EGAD"; } }
jsonrepack(x) // Returns 'EGAD'
There are likely issues with other built-in types as well. To overcome some limitations, additional parameters of JSON.parse
and JSON.stringify
can be utilized.
For example:
function MyClass (v) {
this.date = new Date(v.year,1,1);
this.name = "an object";
};
MyClass.prototype.dance = function() {console.log("I'm dancing"); }
var o = new MyClass({year:2010});
var s = JSON.stringify(o);
// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
if(k==="") {
var rv = new MyClass(1990,0,0);
rv.date = v.date;
rv.name = v.name;
return rv
} else if(k==="date") {
return new Date( Date.parse(v) );
} else { return v; } } );
console.log(o); // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance(); // I'm dancing
console.log(o2); // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]
o2.dance(); // I'm dancing
It is highly recommended to utilize the JSON.parse
method for parsing JSON data.
If you prefer an alternative approach, consider the following:
var myObject = eval('(' + myJSONtext + ')');
Learn more about working with JSON in JavaScript
Find out why using the JavaScript eval function is discouraged
The original JSON object provides developers with two essential methods.
1. JSON.parse()
2. JSON.stringify()
When using the JSON.parse()
method, a JSON string can be transformed back into the original JavaScript object
var jsObj = JSON.parse(jsonStr);
The JSON.stringify() function takes a JavaScript object and converts it to its corresponding JSON format.
var jsonStr = JSON.stringify(jsObj);
What do you think of this solution?
let parsedData = new Function('return ' + serializedJSON )();
A much more secure option compared to using eval
.
let serializedJSON = '{"apple":"banana"}';
let parsedData = new Function('return ' + serializedJSON)();
console.log(parsedData.apple);
Take a look at this incredible resource.
http://jsfiddle.net/RT78Y/
Here's the code snippet:
var data = {};
data.name="codingisfun";
data.age=30;
data.phone=987654321;
debugger;
var dataString = JSON.stringify(data);
alert(dataString);
var newData = JSON.parse(dataString);
alert(newData);
Is this partial solution a viable option?
I am considering storing a global object, called 'bigobj', with both data and methods using a Config node instead of relying on an external library. This 'bigobj' will be used in multiple function nodes within my flow:
It may seem unusual, but it does work: The structure of the global variable 'bigobj':
{
some[]more[]{dx:"here"} , // array of objects with another array of objects. The 'Config' node necessitates JSON.
.....
"get_dx": "function( d,p) { return this.some[d].more[p].dx; }" // a test function
}
In essence, it is a JSON representation of a function.... all condensed into one line.
Implementation: Within a function node:
var bigO = global.get("bigobj");
function callJSONMethod(obj, fname, a, b, c, d){
var wrap = s => "{ return " + obj[fname] + " };"
var func = new Function(wrap(obj[fname]));
return func.call( null ).call( obj, a, b, c, d);
}
msg.payload = callJSONMethod(bigO, "get_dx", 2, 2);
return msg;
This code snippet returns "here", which is quite surprising!
This means I need to include the function callJSONMethod() in every function block that utilizes bigobj.... although this might be acceptable.
Warm regards
I have come across various questions and answers related to this particular issue, but most of them involve using the includes or indexOf methods. The problem at hand is how to filter an array (names in this scenario) using two different arrays - one with ...
I am experiencing an issue with my header.php file on my website. I included another PHP file for my ad code, but it seems to load the ad and then redirect me to a blank page. Can someone please review my code and let me know if there is an error? Thank yo ...
My webpage uses knockout to handle a search field, dropdown selection, and page number. These elements are all initialized with default values for the first run or when the page is accessed. I'm encountering an error that says: "self.selectedTeamId i ...
I am currently working on a WordPress website that features a dynamic background. While I have successfully implemented movement to the background, the content on the site remains static and unaffected by scrolling. The background does not move alongside t ...
Currently, I am delving into React Testing Library, drawing from my extensive TDD experience in various programming languages. The documentation for React Testing Library mentions that if getByText fails, it will "print the state of your DOM under test" h ...
When using React.cloneElement(), the first parameter always needs to be a react component that is passed as children in props. Is there a way to pass a simple HTML node as a child? Please see the example code below for clarification: Dialog.jsx (Common c ...
Every hour, new content is added to a file and saved: with open('data.txt','w') as outfile: json.dump(data,outfile) At any point in time, I retrieve and read the information from this file: with open('data.txt') as json ...
I am having an issue with a dropdown that is set to v-model="compose.Recipient". Based on the value of "compose.Recipient", I need another dropdown to appear as shown below: <div class="form-group" v-if="compose.Recipient==2" title="Select Class"> ...
Currently facing some challenges while attempting to integrate node-vibrant into my Angular 7 project: -Successfully imported with import * as Vibrant from 'node-vibrant';, but encountering a warning in VS Code: Module '"/Users/xxxx/Docume ...
After implementing keyboard key or button navigation in a list of items, I encountered errors during the build phase that do not occur locally. The specific errors are as follows: Error: React Hook "useRef" is called conditionally. React Hooks m ...
Recently diving into the world of backend development, I have been utilizing Node.js on a Replit server with express to host an application for handling files: However, hitting a roadblock when attempting to execute a post request! var express = ...
Currently, I am utilizing the jQuery user interface to adjust the size of a DIV element and also resize the embedded YouTube video within it. For more information, you can visit this link. When the main DIV is resized, the YouTube video should automatica ...
Greetings everyone, I am facing an issue with displaying basic data from an API service that contains a NESTED json object. The challenge I am encountering is that most tutorials only focus on displaying data from array objects, not nested ones. The str ...
My HTML includes a <div>...</div> section that serves as a toolbar. Is there a method to position this section at the bottom of the webpage (document, not viewport) and align it to the center? ...
I have successfully implemented a plugin called List.js in my project. However, I am facing difficulty in adding image src or href values within it. The plugin seems to work well with other tags. If you want to check out List.js, here is the URL: For doc ...
I'm facing a strange issue. I originally used ASIHTTPRequest to fetch data from a web service, and it worked perfectly. However, after switching to NSURLConnection, I'm no longer able to recognize the data even though I receive and parse it in th ...
I am currently using pm2 version 4.2.3 Upon executing the command: pm2 start node launchers/engine_launcher.js --name "engine", it initiates the following processes: id │ name │ namespace │ version │ mode │ pid - ...
Recently, I encountered an issue with the null-coalescing operator while utilizing Json.NET for parsing JSON as dynamic objects. Imagine you have a dynamic object structured like this: string json = "{ \"phones\": { \"personal\": null ...
Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...
I am currently developing a web application using ASP.NET Core - Angular. The app allows users to select a customer as the starting point and then calculates the distance & duration to other customers using Google Maps Distance Matrix Service. Although I a ...