I'm trying to access the age but I cannot, how can I do that?
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(JSON.stringify(json));
This doesn't work for me, obj.carlos is undefined
console.log("Age of Carlos: ", obj.carlos.data.age);
The problem here is the unnecessary call to JSON.stringify, that method is used to convert JavaScript objects to JSON, but has nothing to do with deserializing them.
The code that you need is just this:
var obj = JSON.parse(json);
No need to JSON.stringify. You just only need to parse your values as they are already a JSON string. Here you go:
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);
console.log("Age: ", obj.carlos.data.age);
the problem here is the unnecessary call to JSON.parse(JSON.stringify(json)) conver javascript object to JSON like: JSON.parse(json)
example :
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(JSON.stringify(json));
console.log("Phone of Carlos: ", obj.carlos.data.phone);
You cannot use JSON.stringify() here, because this method converts a JavaScript object or value to a JSON string and you already got a JSON string.
So your code should look like this:
var json = '{"carlos":{"data":{"age":"30","phone":"3226458186"}}}';
var obj = JSON.parse(json);
Related
How can I access a specific data from following JSON without getting undefined?
var myObj = '{"isTrue":"true","id":"1"}';
var theKey = 'isTrue';
alert(myObj[theKey]); //I get undefined here
You need to parse that JSON as String before to access any property from it.
JSON.parse(myObj)
var myObj = '{"isTrue":"true","id":"1"}';
var theKey = 'isTrue';
alert(JSON.parse(myObj)[theKey]);
i used this code in nodejs to get data from json but gets error and say undefined
var obj = {payload:'fp_2'};
var myJSON = JSON.stringify(obj);
console.log(myJSON.payload); //output: undefined
and i have same error in javascript
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var obj = {payload:'fp_2'};
var myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML = myJSON.payload;
</script>
</body>
</html>
what is my error? can any one help me...
obj is already object, you can
var obj = {payload:'fp_2'};
console.log(myJSON.payload);
to parse string to object use JSON.parse
var str = '{"payload": "fp_2"}';
var myJSON = JSON.parse(str);
console.log(myJSON.payload);
JSON.stringify used to convert obejct to string
var obj = {payload:'fp_2'};
var str = JSON.stringify(obj);
console.log(str);
// {"payload":"fp_2"}
What happens in both your example is you are trying to get property "payload" from a string, which does not have this kind of property.
The method JSON.stringify() creates string from any given object, so your custom object with property "payload" was transformed to JS string object, which does not have it anymore.
This is the list of properties, that JS string has:
constructor
length
prototype
You can find definition of each property and read more about strings in JS with this link: W3 Schools JS string
If you want to use "payload" from your custom object, you don't need to JSON.stringify() it. Just use it:
var obj = {payload:'fp_2'};
console.log(obj.payload);
// Or in your html example
var obj = {payload:'fp_2'};
document.getElementById("demo").innerHTML = obj.payload;
write this for nodejs
var obj = {payload:'fp_2'};
console.log(obj.payload);
write this for script file
<script>
var obj = {payload:'fp_2'};
document.getElementById("demo").innerHTML = obj.payload;
</script>
I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);
I'm trying to save some data to localStorage within a containing object. If I were just using javascript variables, I would do this:
var obj = obj || {};
obj.fname = 'bob';
console.log(obj.fname) // => "bob"
However trying to do this in localStorage
window.localStorage.obj = window.localStorage.obj || {}
window.localStorage.obj.fname = 'bob';
console.log(window.localStorage.obj.fname) // => "[object Object]"
Why won't this same technique work for localStorage? Is there a way to do this?
You have to stringify the object and store it in localstorage.
Then when you need it you have to JSON.parse the json string.
var obj = {
b : 2
};
window.localStorage.obj = JSON.Stringify(obj);
var returnObj = JSON.parse(window.localStorage.obj);
localStorage can store only plain string so you need to
window.localStorage.obj = JSON.stringify({fname: 'bob});
Then for reading you need to parse it back so
var obj = JSON.parse(window.localStorage.obj);
console.log(obj.fname);
As mentioned in this answer everything is stored in the localstorage in string format. Hence, in your case the toString method is being called on your obj before it is set. Setting completing objects in the localstorage under some key should be avoid. Try setting the value bob under a key fname in the localstorage using localstorage.setItem('fname', 'bob') or call JSON.stringify on {fname: 'bob'} before setting it in the obj key in the localstorage
I'm trying to initialize an object in typescript which requires a JSON string for the "options" parameter. To be precise it is the object here. The options parameter is required to be a JSON string and not an object for initializing the dijit.
Is there a way to create a JSON string from a typescript object without it being a manual process?
Please DO NOT link any questions which don't specifically say "TypeScript" as this question specifically relates to TypeScript. While a derivative of JavaScript the way that you write code is different and therefore this is the only post asking this question currently relating to TypeScript.
Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.
TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:
JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
JSON.stringify() method converts a JavaScript object or value to a JSON string.
Example:
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';
const JSobj = JSON.parse(jsonString);
console.log(JSobj);
console.log(typeof JSobj);
const JSON_string = JSON.stringify(JSobj);
console.log(JSON_string);
console.log(typeof JSON_string);
You can use the standard JSON object, available in Javascript:
var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);
Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.
const temp = [];
const t = {
name: "name",
etc: [{
a: 0
}],
};
for (let i = 0; i < 3; i++) {
const bla = Object.assign({}, t);
bla.name = bla.name + i;
bla.etc[0].a = i;
temp.push(bla);
}
console.log(JSON.stringify(temp));
If you're using fs-extra, you can skip the JSON.stringify part with the writeJson function:
const fsExtra = require('fs-extra');
fsExtra.writeJson('./package.json', {name: 'fs-extra'})
.then(() => {
console.log('success!')
})
.catch(err => {
console.error(err)
})