I want to create a JSON string inside a JSON request. Here is my code,
Fiddle
JS
var x = {
a: 1,
b: 'a sample text',
};
var request = {
t: JSON.stringify(x),
c: 2,
r: 'some text'
};
console.log(request);
Can someone help me how to escape the double quotes?
Console
Object {
t: "{"a":1,"b":"a sample text"}", //This creates a problem, double quotes inside double quotes.
c: 2,
r: "some text"
}
Thanks in advance.
There is no problem. It's just your console.log that shows all strings by simply delimiting with ".
As you say this request object is used in a JSON request, where it will be JSON.stringifyed another time, with the valid result
{"t":"{\"a\":1,\"b\":\"a sample text\"}","c":2,"r":"some text"}
That's just the way the browser console shows you the value of a string, by wrapping in double quotes for the output. This is perfectly normal and nothing is broken.
You can test it by transforming your JSON string back to an object and using a property.
console.log( JSON.parse(request.t).b ); // a sample text
Well, this may not be helpful. But, I ran into an issue where the JSON string inside a JSON had no property. I was able to parse the JSON string doing the following:
//Return from remote php request {'{"firsttest": 0, ""scndTest": 1"}'};
// How to access
let data = Object.Keys(jsonWJsonString)[0];
let justJSONValue = JSON.parse(data);
this works because there is no object property to reference so an index value can be used; which gives us the JSONString. Hope that helped anyone. Cheers
Related
I have a javascript object that contains a property with values of another json stringified object. I cannot get the printout version of the string back to object form. See the following code. the console.log output content of json string is exactly as right side of jsonFromStr. However, JSON.parse(json) is OK, while JSON.parse(jsonFromStr) is error. What is wrong here?
jsfiddle: http://jsfiddle.net/jma7889/qtmmpj2t/
level2Obj = { key2a: "foo", key2b: 3};
level2ObjJson = JSON.stringify(level2Obj);
level1Obj = {key1a: "bar", key1b: {level2ObjJson}};
json = JSON.stringify(level1Obj);
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\"key2a\":\"foo\",\"key2b\":3}"}}'; // same than json
objFromStrify = JSON.parse(json); // OK
objFromAssignedString = JSON.parse(jsonFromStr); // Uncaught SyntaxError: Unexpected token l in JSON at position 45
If you do this it will work:
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":"{\\\"key2a\\\":\\\"foo\\\",\\\"key2b\\\":3}"}}';
The reason that your version does not work is that the escape sequence \" is resolved at that very moment, and so the actual value of jsonFromStr will be:
'{"key1a":"bar","key1b":{"level2ObjJson":"{"key2a":"foo","key2b":3}"}}'
... which is invalid JSON.
You need to keep those escapes unresolved in the JSON string, and this you do by escaping the escape sequence itself with additional slashes.
jsonFromStr = '{"key1a":"bar","key1b":{"level2ObjJson":{\"key2a\":\"foo\",\"key2b\":3}}}';
You have an extra "" for value of level2ObjJson key,replace jsonFromStr in your code with the above code .
I have div content and div contains text like javascript Object.
<div class="data-content">{ title: "Yes", value : 4247, color: "#FC4349", total_votes: "10968", percentage: "39%"}, { title: "No", value : 6721, color: "#2980b9", total_votes: "10968", percentage: "61%"}</div>
<script> var data = $('.data-content').text();</script>
currently data value is as a string and I want it as object not string.
Is it possible or any other way to get div content as javascript object?
any help is appreciated.
Just try with:
var data = $('.data-content').text();
var output = JSON.parse('[' + data.replace(/\b([a-z_]+)\b/g, '"$1"') + ']');
What happens here ? Valid JSON format requires keys to be wrapped with apostrophes, so we wrap them with /\b([a-z_]+)\b/g regex.
After that we get only objects separated with comma, so we have to wrap it with [] to make an array. Since now it's valid for JSON parser and we get expected result.
http://jsfiddle.net/8ubFY/
Use JSON.parse() as in:
var transformed = JSON.parse(data);
The linked documentation gives details on how to add error handling if your JSON text is invalid. You can also use jQuery.parseJSON() for better browser support as in:
var transformed = jQuery.parseJSON(data);
Okay, so your JSON was also invalid, see JSON object for documentation of valid JSON objects. I have fixed it up and created a JSFiddle to show the correct code.
This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I am trying to parse json source with javascript.
I have this json source:
var exam = '{
status : 'connected',
authResponse: {
accessToken: 'it is accessToken',
expiresIn:'2014-06-19',
signedRequest:'it is signedRequest',
userID:'mp172'
}
}';
To parse, I use JSON.parse(exam);
After this source, it is not working. I want to parse this source with javascript.
Actually, your json source is not valid.
According to JSON.org, member should be quote by "
Change exam to {"status":"connected","authResponse":{"accessToken":"it is accessToken","expiresIn":"2014-06-19","signedRequest":"it is signedRequest","userID":"mp172"}}
Take a look at JSON.stringify and JSON.parse.
var exam = {status : 'connected', authResponse: { accessToken: 'it is accessToken', expiresIn:'2014-06-19', signedRequest:'it is signedRequest', userID:'mp172' }};
// stringify the response first
stringify = JSON.stringify(exam);
// stringified result
console.log(stringify);
// parse the json
final = JSON.parse(stringify);
// parsed final result
console.log(final);
Here is the jsfiddle example
Your JSON is invalid , it should look something like this ,
{
"status": "connected",
"authResponse": {
"accessToken": "itisaccessToken",
"expiresIn": "2014-06-19",
"signedRequest": "itissignedRequest",
"userID": "mp172"
}
}
JSONLint show following error ,
"Proper" json data has both the property name and string values in double quotes. Browser parsers are very lenient though and the reason I think yours is failing is because it isn't a valid string. When you open the string with ', the string ends on the next ' it finds, so it should be choking when it tries to make sense of connected', after finding the string '{ status : '. If you wrapped your JSON in single double quotes (since it uses single quotes for values) that would probably work, but comphilip is right.
If you intended it to be a string to start with, make sure it is in one line. Otherwise, use (+) to append the string and then use JSON.parse to parse it to an object.
var exam = '{"status" : "connected","authResponse": {"accessToken": "it is accessToken","expiresIn":"2014-06-19","signedRequest":"it is signedRequest","userID":"mp172"}}'
var obj = JSON.parse(exam);
I have json like this:
"{'total': 1, 'product_name': 'Cup'}"
After JSON.parse() my result looks like this:
a = {'total': 1, 'product_name': 'Cup'}
If I access a.total I get undefined. If I copy this whole thing in the browser console it's working but not on my app. What is wrong?
Code:
data = "{'total': '1', 'product_name': 'Cup'}";
parsedData = JSON.parse(data);
prod_name = parsedData.product_name;
"{'total': 1, 'product_name': 'Cup'}" is valid JSON - it's a single string with the value {'total': 1, 'product_name': 'Cup'} (i.e. it looks like an object but isn't one!).
Instead, you need to pass a string with the value {"total": 1, "product_name": "Cup"} to JSON.parse (i.e. no quotes outside the braces and double quotes for strings).
If you do this in JavaScript, it would look like so:
data = "{\"total\": 1, \"product_name\": \"Cup\"}";
parsed = JSON.parse(data);
As you can see, you need to escape the quotes :-)
Your JSON is invalid. JSON strings must be quoted with " not '.
Do test your JSON
Avoid writing JSON by hand
Avoid using JSON when you can use JavaScript
Such:
parsedData = {'total': 1, 'product_name': 'Cup'}
console.log(parsedData)
{'total': 1, 'product_name': 'Cup'}
console.log(typeof(parsedData))
string
If that is the case, then your JSON is valid, but it is just a JSON text containing a single string.
Get rid of the " around the JSON as well as changing the ' inside it to ".
So basically I have this code:
var string = '{name: "bob", height: 4, weight: 145}';
I would like to know if it is possible to convert that string into an object.
so that I can use
string.name, string.height, and string.weight
(I am retrieving the string variable from a database so I cannot just remove the quotes and make it an object in the first place)
eval, as suggested by Igor, will certainly work but is vulnerable to attack.
Instead you could use a library to parse it for you. There are options in the following link:
Eval is evil... So what should I use instead?
It seems that your string is malformed. In order to work with JSON.parse or even jQuery.parseJSON methods, your keys must have speech marks (" ) around them, like so:
var str = '{"name": "bob", "height": 4, "weight": 145}';
var obj = JSON.parse(str);
You can test this by adding console.log(obj); as the final line. Here is my jsFiddle example.
So try to see if you can pull down the data from the server in the format I have suggested and it can then easily be parsed into a JavaScript object.
I would not use string for a variable name, but:
var obj = eval(string);
alert(obj.name);
or you can use jQuery.parseJSON: api.jquery.com/jQuery.parseJSON.