So I have to edit an entire array and decided to copy it from google, it returned to me this:
{
"name": "Tom",
"age": 20
}
...
Is it possible to copy the array without the "" around the object name? Or is there another way of doing this?
Use JSON.parse() to parse the data
https://www.w3schools.com/js/js_json_parse.asp
Related
I am obtaining the response from the server in JSON format. This JSON may constitute objects with duplicate Keys. When I was displaying the result the duplicate key values were getting committed. After debugging I found out that this is happening because of the JSON.stringify method that I am performing to format the code before providing to the front-end.
As of now when I perform the JSON.stringify then it removes the duplicate entries and provides only the last value for the duplicate keys however I would like to retain everything.
var obj = {name: "John", age: 30, name: "New York"};
var result = JSON.stringify(obj).replace(/\_/g, '');
console.log(result);
//{"name":"New York","age":30}
As we can see the first name has been committed. How to modify the code so we can retain all values of the duplicated key?
Please Note:
As of now, I have provided the sample code that has the duplicate key name. However, when I am getting the response from the server I am unaware of what key might be duplicated so I am looking for a general solution that can work for everything rather than hard-coded logic that works only for name.
Any suggestions or workarounds would be really appreciated.
Json objects don't allow duplicated keys.
If you execute just:
var obj = {name: "John", age: 30, name: "New York"};
console.log(obj)
You will see that you have already lost the first "name" value.
The only work around that I can think of, is to never transfor the received JSON String to an Object.
Or you can manually write a logic to split this json string by commas, and transform it into a JSON object according to you need, but without duplicated keys, for example:
{name: ["John", "New York"], age: 30};
This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined
How can I store an object/array in JavaScript Cookies?
I tried that simple code
var item = {
price: 200,
company: 'Microsoft',
quantity: 500,
code: 'm33'
}
console.log(item);
Cookies.set('item', item);
console.log(Cookies.get('item'));
It shows all the values in the first console message, but gives only "[object Object]" in the second. Looks like js-cookie cannot work with objects correctly. Is there any way I can fix that?
You are storing an object, and cookies are allowed text-only. Remember that cookies have a max-length of 4 KB, so you can't store a lot of information here (use localStorage instead).
To solve this problem, you must to stringify the json first:
Cookies.set('item', JSON.stringify(item));
And you'll store a stringified object. To access it then, you must to parse the string:
console.log(JSON.parse(Cookie.get('item')));
Just use:
Cookies.getJSON('item')
js-cookie has built-in support for JSON parsing as from version 2.0.0, there is no need to change how you set it. For more information, see https://github.com/js-cookie/js-cookie/tree/v2.1.0#json
In cookie you can only store string. So in order to store object first you convert your object into string. Using this plugin here is an example:
var people = [
{"id": 123, "name": "Mazahir Eyvazli"},
{"id": 128, "name": "Mayki Nayki"},
{"id": 131, "name": "Mike Shinoda"}
];
$.cookie("people", JSON.stringify(people));
If you want to access your people as an object from cookie
// $.cookie("people") will return people object as an string
// therefore we parse it to JSON object
var people = $.parseJSON($.cookie("people"));
// now we can access our object
people[0]["id"] // --> 123
people[1]["name"] // --> Mayki Nayki
After searching online and not finding anything, I decided to post here.
What I have so far:
JSON
I have a JSON file, with several list of words that I need to retrieve according to user input. They look something like this:
{
"length": 10,
"targetWords": {
"SOME_NAME": [
{
"words": [
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz",
"xyz"
]
},
{
"text": "Some example text",
"letter": "X",
}
],
}
localStorage input
I ask the user to choose an option and "record" that answer in a variable. Let's call it "userInput".
userInput = localStorage.getItem("something")
I get the JSON and pass it to a variable (I'm using Phaser Framework)
TARGET_SOUNDS_DATA = this.game.cache.getJSON('targetSounds')
What I want now is to access the values inside it. I can do it if I go about it like this:
TARGET_SOUNDS_WORDS_ARRAY = TARGET_SOUNDS_DATA.targetWords.SOME_NAME[0].words
But unable to do so if I use the user answer/input like this:
TARGET_SOUNDS_WORDS_ARRAY =TARGET_SOUNDS_DATA.targetWords.userInput[0].words
This way I only get undefined
So I know I'm doing something wrong but what?
Any help/hints are welcomed! Thanks for your time!
Cheers,
J
You can use square brackets to select a property with a variable
TARGET_SOUNDS_WORDS_ARRAY = TARGET_SOUNDS_DATA.targetWords[userInput][0].words
You have to parse it and then to get result based on userInput access it like this
TARGET_SOUNDS_WORDS_ARRAY =TARGET_SOUNDS_DATA.targetWords[userInput][0].words
As I understand, and maybe I'm wrong, localStorage is key/value storage only. You'll have to convert the json to a string, store it, then retrieve it and convert it back to an object when you want to use it.
I am trying to figure out if I JSON.Stringify an object like this:
{"m_id":"xxx","record":
{"USER":"yyy","PWD","zzz","_createdAt":
11111."_updatedAt":00000},"state":"valid"}
and then try to JSON.Parse out only the USER and PWD, not have to just call the object, but go through stringify. how would that work?
thanks.
I'm not sure why you're talking about stringifying your object. You'd stringify it if you needed to send the data across a network or something, not when you need to manipulate it in JS.
...how do I extract the strings in {...USER: "aaa", PWD: "zzz"...}?
Assuming you have a variable referring to the object, something like the following (with or without nice line breaks and indenting to make it readable, and with or without quotes around the property names):
var obj = {
"m_id": "xxx",
"record": {
"USER": "yyy",
"PWD" : "zzz",
"_createdAt": 11111,
"_updatedAt": 00000
},
"state": "valid"
};
Then you can access the properties in the nested record object as follows:
console.log( obj.record.USER ); // outputs "yyy"
console.log( obj.record.PWD ); // outputs "zzz"
// etc.
(Note: in your question you had two typos, a comma that should've been a colon in between "PWD" and "zzz", and a dot that should've been a comma in between 11111 and "_updatedAt". There's no way that JSON.stringify() would have produced the string that you showed with those mistakes.)
If you want the strings "USER", "PWD" etc as an array, then use Object.keys.
If you want to iterate them, just use a normal for-in enumeration.
I might have misunderstood the question, but if I think it is what it is then try using
var tmp = JSON.parse(string_to_convert)
this should suffice to convert your string to a proper Javascript Object
Then you can do
for(var index in tmp){
console.log(tmp[index]);
}
and this should list all the keys on the first set of properties. If you want to do a nested thing, then use recursion on the properties. Hope this makes sense...