javascript parse string as object or JSON - javascript

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?

Related

Adding quotation makes to JSON String which contains some XML values

I'm trying to format a JSON input string in Javascript so that I can use it as a map.
{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}
To do this I need to put quotation marks around each key and value. Like here:
{
"accountNumber": "12345",
"paymentMethodObject": "<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>",
"preview": "true"
}
The problem is when I try to do it, quotes get added to the XML values also because they also contain a colon.
Maybe you need to use method replace with pattern Regex that match key:value replace it with surrounded by quotes pair!
let strJSON = '{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}';
let objJSON = strJSON.replace(/(\w+):([\/<>:\w+]+)/g,'"$1":"$2"');
console.log(objJSON)

JS - parsing data with random single quotes

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 array in double quotes back as original array in Javascript

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.

Javascript Set Attribute With Single Quotation

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

Why is stringified JSON a valid string?

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.

Categories