Fix JS object replacing/encoding of strings? - javascript

I have an object with a value that has spaces in it, and it gets replaced with an encoded string, like:
alldata["test"] will return "Long+name"
or something like
alldata["test"] will return "%BLong+name%B"
when it's set by using
alldata["test"] = "Long name" (or "[Long name]") via a series of code.
Am I missing something? I don't think using $.toEvalJSON is the right way to go because I haven't transformed the object into JSON. I'd rather not do a string.replace either because I'd have to capture every possible type of input that is encoded.
Thank you!

If your question is how to remove the encoding, you could always use
unescape(s)
See Escape and Unescape Functions

The issue is related to the fact that I failed to mention that the object was being assigned the string as a result of a .serialize() command. Hence a urldecode() will work perfectly.

Related

Why is the browser changing my single quotes to double and ruining my JSON in the data attr?

This should be way easier than it is, but it's got me stuck.
Im putting some JSON in an input data attribute and the quotes on the first key are closing the attribute.
Here's what I'm trying to do:
var html = `<input type="checkbox" data-values='${dataVals}' />`;
Where dataVals is a JSON string like this
'{"checked":true,"unchecked":false}'
But it's showing up in the browser like this:
<input type="checkbox" data-values="{"checked":true,"unchecked":false}">
And the browser is reading it essentially as though it's this.
data-values="{"
Which obviously isn't what I want.
I'm clearly missing something. Any thoughts?
Combination of #T.J. Crowder and #Teemu
I added a replace at the end of the json string to replace double quotes with "
JSON.stringify({ ... }).replace(/\"/g, """)
Then also stopped trying to run JSON.parse() when I wanted to get the value later since $.data('values') already returns a javascript object (when it can).
JSON.parse($(this).data('values')) => $(this).data('values')

Setting an element value using HTML entities

I'm having an issue trying to set an input field's value when using HTML entities in that they are coming out literally as " rather than ".
Here is the code I am using:
document.getElementById('inputSurname').setAttribute('value', 'test"""');
in which the output is test""" though I want the output to be test""".
It doesn't look like a double-encoding issue since in the source code I am seeing it the same way I have set it here.
I know I could decode the value from its HTML entity format though this is something I want to avoid if possible for security.
Any help would be much appreciated :)
Try this:
document.getElementById('inputSurname').value = 'test"""';
Or if you want to keep &quot:
function myFunction() {
document.getElementById('myText').value = replaceQuot('test&quot&quot&quot');
}
function replaceQuot(string){
return string.replace('&quot', '""');
}
Or you can use escape characters.
document.getElementById("inputSurname").setAttribute("value", "test\"\"\"\"");
Well you could just write the new value as 'test"""'.
For other characters however, I'm going to refer you to this answer: HTML Entity Decode

Extracting values with Javascript

I have a variable called "result",
var result;
that result value is equal to following value, please presume that is just a string :)
---------result value -----------
for (;;);{
"send":1,
"payload":{
"config":{
"website":"",
"title":"welcome to site",
"website-module":1313508674538,
"manufatureid":"id.249530475080015",
"tableid":"id.272772962740259",
"adminid":100002741928612,
"offline":null,
"adminemail":"admin#website.com",
"adminame":"George",
"tags":"web:design:template",
"source":"source:design:web",
"sitelog":[],
"errorlog":0,
"RespondActionlog":0,
"map":null
},
"imgupload":""
},
"criticalerror":[0],
"report":true
}
---------result value------------
From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.
How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.
You can simply evaluate the value of the variable to obtain the values. However, please note that your current value is not valid JSON; that for(;;); at the beginning of the value invalidates the format. Remove that, and you can do this:
var object = eval('(' + resultMinusThatForLoop + ')');
alert(object.payload.config.tableid);
If that data is a string the parse it with a JSON parse. The following should get the value you want
JSON.parse(result).payload.config.tableid; // "id.272772962740259"
Edit: though, as Tejs says, the for(;;) invalidates the string and stops it from being parsed. If you can remove that, do.
You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.
You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.
If result is a javascript object and not a string, you can just use 'result.payload.config.tableid'.
If it is not, how do you get the AJAX result? Are you using XmlHttpRequest directly? Most libraries will give you a javascript object, you might be missing a flag or not sending the response back with the right content type.
If it is a string and you want to parse it manually, you should use a JSON parser. Newer browsers have one built in as window.JSON, but there is open source code for parsing it as well.
var obj = JSON.parse(result);
alert('tableid is ' + obj.payload.config.tableid);

javascript object value to string conversion

I am getting the value of input using javascript using below code.
var name=document.getElementById("firstName").value;
Getting output like rk-chaitu.I want to split this output using reg expression.
Now my question is how to convert name object to String?
Regards,
Chaitu
name should already be a string. You can directly use name.split(separator).
EDIT: I see you have added information. Can you post more code? Perhaps the error comes from something else.
The value attribute should already be a String.

Is JSON.parse supposed to be recursive?

I am parsing a json string like so:
ring = JSON.parse(response);
Now, ring is an object but ring.stones is just a string when it should be an object as well.
If I call:
ring.stones = JSON.parse(ring.stones);
It is now the correct object.
I didn't know if this is correct behavior or if maybe I have an issue somewhere stopping it from parsing recursively? If it is supposed to parse recursively, are there any known issues that would prevent it?
Update
Here is the full response before parsing:
{"ring_id":"9","stone_count":"4","style_number":"style 4","syn10":"436.15","gen10":"489.39","syn14":"627.60","gen14":"680.85","available":"yes","type":"ring","engravings_count":"0","engravings_char_count":"0","engravings_band":"10","stones":"[{\"stone_id\":\"27\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"132.80\",\"stone_y\":\"114.50\",\"stone_width\":\"71.60\",\"stone_height\":\"71.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"1\",\"stone_mm_width\":\"5.00\",\"stone_mm_height\":\"5.00\"},{\"stone_id\":\"28\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"100.50\",\"stone_y\":\"166.20\",\"stone_width\":\"36.20\",\"stone_height\":\"36.60\",\"stone_rotation\":\"0.00\",\"stone_number\":\"2\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"29\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"200.20\",\"stone_y\":\"105.10\",\"stone_width\":\"33.90\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"3\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"},{\"stone_id\":\"30\",\"ring_id\":\"9\",\"stone_shape\":\"round\",\"stone_x\":\"165.80\",\"stone_y\":\"82.50\",\"stone_width\":\"35.50\",\"stone_height\":\"33.90\",\"stone_rotation\":\"0.00\",\"stone_number\":\"4\",\"stone_mm_width\":\"2.50\",\"stone_mm_height\":\"2.50\"}]","images":"[{\"title\":\"white gold\",\"source\":\"Style4_4_W_M.png\"},{\"title\":\"yellow gold\",\"source\":\"Style4_4_Y_M.png\"}]"}
Update 2
Based on mikerobi's answer I was able to figure out what was happening:
Here is where I encoded it:
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row['stones'] = getStones($ring_id);
$row['images'] = getRingVariations($ring_id);
return json_encode($row);
But the functions getStones and getRingVariations were returning json_encode'd strings. I needed to change them to return plain strings.
Your JSON structure is wrong, it is wrapping stones in quotes, turning it into a string.
Your JSON looks like:
{
stones: "[{\"stone_id":\"27\"},{\"stone_id\":\"27\"}]"
}
It should look like:
{
stones: [{"stone_id": 27},{"stone_id": 27}]
}
EDIT
It appears you are converting all values to string, including numbers, I updated my example to reflect this.
Also, I'm guessing by the output that you are writing your own code to serialize the JSON, I highly recommend using an existing library.
It is recursive, but your input string (response) is not in correct format. Get rid of those escape characters (\") and try again.

Categories