I have the following code:
localStorage.setItem("ActiveDataOfpModel", iHandle.find("ul li.pModel.active"));
When i check "ActiveDataOfpModel" value in console i get "[object Object]".
How can i store the actual object in "ActiveDataOfpModel" and retrieve its properties. i.e. i want to do the following:
var value = localStorage.getItem("ActiveDataOfpModel").attr("data-id")
i did try
var value = JSON.parse(localStorage.getItem("ActiveDataOfpModel")).attr("data-id")
but its not working
You can only store strings in local storage.
You can encode simple objects as JSON (they must contain only JSON data types such as objects, numbers, and strings) as a string using JSON.stringify(someObject).
var value = JSON.parse(localStorage
… and that is how to convert the JSON back to an object afterwards.
Your code iHandle.find("ul li.pModel.active") implies you are not dealing with a simple object though. That is something I would expect to return a DOM element or something akin to it.
You would need to extract the data you care about from it, store that in an object, store that in the JSON and then the localstorage, and write more code to convert the simple data back in to the full object when you pull the data out afterwards.
Try this:
Convert it to String before saving to LocalStorage
localStorage.setItem('key', JSON.stringify(data));
Convert back to JSON object, when reading from LocalStorage
data = JSON.parse(localStorage.getItem('key');
Related
console.log(JSON.stringify(body));
this is a log from above code.
"{\"result\":{\"normal\":0.002,\"soft\":0.776,\"adult\":0.222}}"
this is a result of json String but I can't how to parsing normal, soft, adult value
To parse the JSON string just use indexing on the key's value. Something like this would help you retrieve the value of normal in the JSON object:
console.log(body['result']['normal']);
Read up more about the JSON object and how to handle them: https://www.w3schools.com/js/js_json_objects.asp
So, I used data declared by myself, but now i switch the code to LocalStorage, and I'd like to know, how to get the data from one element of LocalStorage, and insert it to a block of data from my program.
Here's a part of code which shows the procedure which i use for inserting data
let l = this.lists;
localStorage.setItem('lists', JSON.stringify(l));
l is of type string, and lists is an array with data block.
I wanted to use this command
this.lists = localStorage.getItem('lists');
but unfortunately,it wants a string element, and doesn't want to work with my lists element...
Info time:
LocalStorage is implementation of Storage interface and it accepts and
returns plain strings so every time you want to store there something
a little bit more complex you have to serialize when inserting
(JSON.stringify) and deserialize when retrieving (JSON.parse)
You can use JSON.parse()
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.
this.lists = JSON.parse(localStorage.getItem('lists'));
localStorage is implementation of Storage interface, It works on plain strings. When you want to work with complex object serialize it using JSON.stringify() and deserialize using JSON.parse()
I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.
I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");
This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)