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}");
Related
I am experiencing an issue where I am in need of passing a JSON as an HTML attribute. I have the JSON string:
{"filename":"myFile.js","content":"var k = 'My Value'"}
Which I am passing to a html attribute:
<ide file-json='{"filename":"myFile.js","content":"var k = 'My Value'"}'></ide>
The issue occurs where var k = 'My Value' as the ' mark is unescaped and causing the html parser to think the value of attribute file-json is {"filename":"myFile.js","content":"var k = rather than the full string. The file-json attribute is going to be read via javascript for additional processing.
The values for both the json keys of filename and content are user generated, and can have almost any value. Is there a way escape the entire file-json attribute?
Things that I have already tried, and the reason for their failure are below: (The actual json input can be extremely large.)
Use a giant regular expression to escape any offending instances in the json file. This for two primary reasons, the first being that it was slow, but more importantly it is a "dumb" solution and often makes mistakes causing additional errors, and data corruption.
Convert the entire json structure into base64/hex; pass this encoded structure to file-json; and then in the javascript when it is read, convert it from base64 back into a json string; and finally continue processing. This so far is the best solution that I have come up with as it is the only one that cannot cause data corruption. However it is both slow and consists of a large number of moving parts leading to issues in maintainability and expandability.
Your json looks like valid json, so a simple JSON.stringify should do the job
var json = {"filename":"myFile.js","content":"var k = 'My Value'"}
var stringified = JSON.stringify(json);
// or whatever element identifier you have
document.getElementById('foo').setAttribute('file-json', stringified)
if not and its really a string, simply add JSON.parse()
var stringified = JSON.stringify(JSON.parse(json));
FIDDLE
I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode
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.
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)
I know that I can create an associative array like this:
var MyAssocArray = {'sky':'blue', 'grass':'green'};
And I am very fond of using this method.
What I would like to do and am having trouble with is this:
I have strings saved like this:
var MyString = "'sky':'blue', 'grass':'green'";
And I want to be able to do this now:
var MyAssocArray = {MyString};
When I try that - I get this error:
invalid object initializer
What am I doing wrong?
How can I achieve this?
I found a different solution using PHP and JavaScript. The associative array string is echoed in the JavaScript code:
var Multidimensional_Arr[Multidimensional_Array_Key_Name] = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
// The same can be done for a one-dimensional array
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
Use JSON -- it's serialized JavaScript Object Notation and is pretty close to what you're doing.
You'd need to do
var MyAssocArray = JSON.parse(MyString);
Also, JSON uses double quotes, not single quotes; if you use simple objects, you can probably write code to just replace ' with "" in your strings, but it's tricky if the strings contain double-quotes.
If you are using a browser that doesn't implement JSON.parse(), you can either use the implementation on the JSON website (see links at bottom of this page) or if you're using jQuery, there's jQuery.parseJSON().
Warning: Your solution has a security risk, unless you are sure the data in the database has been sanitized:
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}
This is equivalent to a call to eval(); if your database string has any malicious code it can do bad things. This is one reason why JSON was invented -- it's easy to ensure that its contents are valid (and hence safe) before evaluated.
Your overall architecture, as you have presented it to us, is [data in database] -> server-side PHP -> client-side JavaScript. This is a classic example of serialized data. I realize you may have constraints to keep your system running without interruption, but a strict serialization format would make your system more secure.
If you are sure the data is safe, then you could do:
var MyAssocArray = eval('{' + MyString + '}');
You can't do that.
To achieve what you want, use the split() function to split your string into comma-separated tokens first. Then each token should further be split by the ':' character.
Then push the two tokens obtained by the last split as the key and the value of your associative array.