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
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
So say I have a JSON object like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
And I can't modify it when it is created. But I want to make it look like this:
{"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI", checked: true}
So how would I do that with javascript?
In the context of JavaScript, there's no such thing as a "JSON Object". What you've got there are JavaScript objects. JSON is a data interchange format that was of course derived from JavaScript syntax, but in JavaScript directly an object is an object. To add a property, just do so:
var object = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"};
object.checked = true;
Now, if what you've really got is a string containing a JSON-serialized object, then the thing to do is deserialize, add the property, and then serialize it again.
With the way your question is currently structured:
> myJson = {"name":"asdf","quantity":"3","_id":"v4njTN7V2X10FbRI"}
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI"}
> myJson.checked = true;
true
> myJson
Object {name: "asdf", quantity: "3", _id: "v4njTN7V2X10FbRI", checked: true}
But I bet you may have to decode and recode first with:
JSON.parse(myJson)
JSON.stringify(myJson)
The entire thing may look like
// get json and decode
myJson = JSON.parse(response);
// add data
myJson.checked = true;
// send new json back
$.post('/someurl/', JSON.stringify(myJson));
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...
I am trying to create a JSON object in the particular format
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
// My code starts here
var number = userid; // alert(userid) is 12345
var name= nameuser; // alert(nameuser) is Alex
var g= gender; // alert(gender) is male
var userObj = { "id": number , "name": name , "gender":g}
I tried `JSON.stringify(userObj); ,
that returns the object type as
{"id":"12345" , "name":"Alex" , "gender":"Male"}
but this is not what I want as I want the number to be 12345 and not "12345".
also tried stringifying the fields inside the object like
{ "id": number , "name":JSON.stringify(name) ,gender: JSON.stringify(g)}
but when I do alert(userObj) my object type is Object object and this is not a format the server recognises.
I am sure there is a workaround for this but I am unable to figure one out
JSON works with strings exclusively. It's invalid to have anything other than a string, array, or other JSON object in JSON. That said, a "number" is not allowed; it needs to be a string. Whatever you are working with with the JSON later needs to be able to change the string back it to a number, if necessary. JavaScript usually does a good job of coercing these.
On the server side you can just do something like
obj = json_decode(source)
obj.id = (int)obj.id
I think that your solution will come down to what you want to DO with the JSON, rather than how you want it to be formatted.
If you're using it in other JavaScript code, then the JSON.parse method is going to take care of most of your issue on the other side (with automatic type-casting dealing with the rest).
If you're using it on the server-side, again, PHP or similar will decode the object appropriately.
And if it's a more-strict language on your server, all you need to do is remember which parameters need to be cast to boolean or to int/float.
The below code from your question is valid JSON.
{ "id": 12234 , "name": "Alex" , "gender": "Male"}
I am guessing that the problem you have is that your userid variable is a string, not a number. If so, try
var number = parseInt(userid, 10);
(The 10 parameter indicates that you are using base 10 numbers as opposed to something like binary or hex).
store the object type as one of the property and use it to convert the way you want.