Can't access JSON values - javascript

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 ".

Related

json - can't access json parameter

Here is my code
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
var json = JSON.parse(JSON.stringify(data));
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
And I can't seem to figure out why I'm not able to access the json object parameter. Anyone know what the issue is?
Thanks in advance.
Let us to some basic debugging:
> var data = '{"coord": ... }';
> typeof data
"string"
So far so good, data is a string.
> JSON.stringify(data);
""{\"coord\": ... }""
> typeof JSON.stringify(data);
"string"
Apparently JSON.stringify(data) also returns a string. We can see the same value contained in data but now including surrounding quotes (note the double "" at the beginning and the end) and escaped quotes (\").
So what exactly does JSON.stringify do? It will convert any JavaScript value to JSON. Some examples:
> JSON.stringify([]) // array
"[]"
> JSON.stringify(true) // array
"true"
> JSON.stringify("foo") // string
""foo""
We can see that passing a string simply produces another JSON encoded string, so that doesn't seem particular helpful. But you are also using JSON.parse, so lets see what effect that has:
> JSON.parse(JSON.stringify(data))
"{"coord": ... }"
> typeof JSON.parse(JSON.stringify(data))
"string"
It seems using JSON.parse returns a string again. This shouldn't be too surprising since we are passing a string value to JSON.stringify, which will encode it as a JSON string. Parsing this result must give us back the original value, which was a string. We can verify that easily:
> JSON.parse(JSON.stringify(data)) === data
true
Yep.
So that doesn't help us converting data to a JavaScript object. Lets just try JSON.parse instead:
> JSON.parse(data)
Object {coord: Object, weather: Array[2], base: "cmc stations", main: Object, wind: Object…}
That looks much better. Since data contains a JSON encoded object, JSON.parse converts that value to a JavaScript object.
I your example, data is a string, not a javascript object, so you don't need to use JSON.stringify, remove it and it should work:
var data = '{"coord":{"lon":74.34,"lat":31.55},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"cmc stations","main":{"temp":304.6,"pressure":1002,"humidity":62,"temp_min":304.15,"temp_max":305.15},"wind":{"speed":5.1,"deg":130},"clouds":{"all":20},"dt":1466901000,"sys":{"type":1,"id":7133,"message":0.0035,"country":"PK","sunrise":1466899176,"sunset":1466950287},"id":1172451,"name":"Lahore","cod":200}'
setWeather(data);
function setWeather(data) {
//NOTE: only parse is needed
var json = JSON.parse(data);
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}
data is a String because of the single quotes , so if you called JSON.stringify(data) will add another double quotes to data , which means in order to convert data to JS object you will need to call JSON.parse(data) two times .
var obj ='{hello:1}'; //string
var json= JSON.stringify(obj);
console.log(json); // "\"{hello:1}\""
console.log(JSON.parse(json)); //"{hello:1}" => still a string
To get your code running correctly by converting data to object , just remove the JSON.stringify()
function setWeather(data) {
var json = JSON.parse(data); // remove JSON.stringify() => now json is object
alert(json['main']['temp']);
$('#temp').html(json['main']['temp']);
}

JSON String inside a JSON

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

javascript String to JSON?

I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u
That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.
In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}
You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')
The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);
JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"

String to Object

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.

Can I use a variable to pass a json string?

This code works:
$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});
This code doesn't work:
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);
The question is, how can I make it work?
Your data is not a Javascript object but a string, you can convert it to object by eval e.g.
data = eval('(' + data + ')');
but eval is considered dangerous, so better to parse string as JSON e.g.
data = JSON.parse(data)
For JSON lib you can use json2
It's not JSON, it's a javascript object.
var data = { category: 1 };
If you have a string, you would have to convert it to a object.
And notice that your string is not a valid JSON, see the link for more details.
Take out the quotes, the load function is expecting an object, not a string.
Have you tried to use eval() on data?
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));

Categories