It seems that by default javascript appends attributes using double quotes. However in my situation I am attempting to append a json string to a data attribute and the double quote interferes with the json.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json)); //<div data-json="{"foo":"bar"}">
How can I append an attribute using a single quote?
It is incorrect to say that
by default javascript appends attributes using double quotes.
An attribute is merely a string. The attribute value itself does not include the surrounding quotes. Quotes are nothing more than syntax for representing a string literal. The outside quotes you see surrounding the attribute in
<div data-json="{"foo":"bar"}">
do not exist in the attribute value; they were simply inserted by the console when it is printing out the attribute for your visual convenience. There is nothing "interfering with the JSON". The attribute value can be retrieved and parsed with JSON.parse as is with no further ado.
var json = {"foo":"bar"}
var el = document.getElementById("someElement");
el.setAttribute("data-json", JSON.stringify(json));
// now, parse the attribute
>> JSON.parse(el.getAttribute('data-json'))
<< Object {foo: "bar"}
I think the better practice is string escaping (see adeneo's answer).
But just as an other option you may be able to replace double quotes with single quotes by .replace() function:
var json = {"foo":"bar"}
var encoded = JSON.stringify(json);
encoded = encoded.replace(/\\"/g, '"')
.replace(/([\{|:|,])(?:[\s]*)(")/g, "$1'")
.replace(/(?:[\s]*)(?:")([\}|,|:])/g, "'$1")
.replace(/([^\{|:|,])(?:')([^\}|,|:])/g, "$1\\'$2");
var el = document.getElementById("someElement");
el.setAttribute("data-json", encoded);
Attention the result string "{'foo':'bar'}" is not a valid json
Related
I am inserting a json string value as a value of a button element attribute,
like for example below
var $json = JSON.stringify('{"Long_text":"This is \'my json string and soon..."}');
$("#button_id").attr('data-json', $json);
This works in some of my pages but when there is a single quote in the text even if it is escape with a slash the value in the element attribute creates newline and it breaks
like:
<button data-json="{"Long_text":"This is \' "
"my json string and soon..."}" >Click</button>
I have tried using
replace('/\r?\n|\r|\n/g/',''); //to replace multiple newlines
Even if I replace the double spaces it doesn't work because the attribute itself was malformed. So when I get the attribute and try to parse the json value it cause an error.
I have found this,"->Line break inside HTML tag attribute value" should I replace the spaces with this %0D%0A ? as suggested
to preserved newlines or spaces?
Any help or advise is well appreciated! Thanks!
I found a solution other than replacing the spaces with this %0D%0A
from this Line break inside HTML tag attribute value
var base64 =
{
encode: function utoa(str)
{
return window.btoa(unescape(encodeURIComponent(str)));
},
decode: function atou(str)
{
return decodeURIComponent(escape(window.atob(str)));
}
}
I tried this and it works, it also make the string non-readable since it is base64_encoded, it avoid the line breaks caused by spaces and quotes.
var $json = base64.encode(JSON.stringify('{"Long_text":"This is \'my json string and soon..."}'));
$("#button_id").attr('data-json', $json);
then get the value and convert it again,
var valid_json = JSON.parse(base64.decode($("#button_id").attr('data-json')));
Thanks!
How do I parse an array of objects if it contains single quote characters?
For example, I have:
$example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
The single quotes seem to break up the array, making parsing impossible.
You can use backticks (``). It will generate the string as it was written, with double "" and single ' quotes.
var str = `{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}`;
console.log(str);
var obj = JSON.parse(str);
console.log(obj.response[0].uid);
It's a json string not an object.
Use JSON.parse(myJsonSting) and you will get objects with the ' taken care of.
Javascript is supposed to ignore single quotes if it is inside double quotes, in your case try adding backslash before the single quote.
To parse at json string to object
var example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
var objExample = JSON.parse(example);
To convert json object to json string
var StrExample = JSON.stringify(objExample);
How to convert this string into original array in Javascript?
var str_arr = "["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410]"
like I want to store it back as original array
var arr = ["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410];
You have a syntax error in your str_arr.
var str_arr = '["myName","asldkfjs","2342","sbc#lkjsf.com","sdlkfjskldf",410]';
var arr = JSON.parse(str_arr);
You could try parsing it as JSON, because an array is valid JSON (assuming it uses double quotes for the strings).
arr = JSON.parse(str_arr);
Also, as #manonthemat mentioned, you need to either use single quotes to wrap the string literal where you declare str_arr (since it contains double quotes) or you need to escape the double quotes to avoid a syntax error.
We're already aware that we cannot add double quotes inside the double quotes:
var str = ""hello""; //this will be invalid string
but when I stringify an object like this
var obj = {"name":"abc"}
var str = JSON.stringify(obj).
str // returns "{"name":"abc"}"
which is valid but shouldn't be. I'm confused as in do JavaScript have some special cases when we stringify a JSON object and omit the string validations on it?
Thanks in advance.
You can have as many double quotes inside a string literal as you want. You just need to scape them using a backslash prefix (\" instead of ").
Try this example in your browser console:
var myStr = "\"Hello\"";
myStr
You should see ""Hello"" in your console. That would be how the stringify creates a string with double quotes in it.
I want to be able to define a hash pair inside an html element as an attribute and then parse it into an object to be processed by javascript.
example:
<div id="test" mydata="{'xkey':'xval','ykey':'yval'}">
<script>
var mydata = JSON.parse($('#test').attr('mydata'));
console.log(mydata.xkey);
</script>
But the problem is it is not being converted into an object and the output is undefined.
How can I achieve this ??
Use double quotes instead, to surround keys and string values:
mydata='{"xkey":"xval","ykey":"yval"}'
DEMO: http://jsfiddle.net/reAtQ/
If you must keep the surround double quotes, you can encode the inner ones:
mydata="{"xkey":"xval","ykey":"yval"}"
DEMO: http://jsfiddle.net/reAtQ/1/
Or, you could replace all single quotes with double quotes before parsing:
var mydata = JSON.parse($('#test').attr('mydata').replace(/'/g, '"'));
DEMO: http://jsfiddle.net/reAtQ/2/
Although note that if any of the keys/values contain a single quotes, they will be inadvertently replaced.
Reference:
in JSON, Why is each name quoted?