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']);
}
Related
I'm using Editor.js which outputs data as JSON and save that as String in DynamoDB. When I query that data, I want to convert that back to an Object.
Converting the string with JSON.parse() gives me Error: Unexpected token t in JSON at position 1 message.
var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);
Not sure what this error message means.
I will suggest to correct the JSON from the origin itself if you can,
if you can't than you need to replace = with : and than stringify and parse
({[^=]+|,[^=]+)=
| |_________ Replaces `=` which is preceded by `,`
|_________________ Replaces `=` which is preceded by `{`
let json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
json = json.replace(/({[^=]+|,[^=]+)=/g,"$1"+':')
let obj = JSON.parse(JSON.stringify(json));
console.log(obj)
On side note:- This is code is considering above given example data, it can be updated based on the kind of values your JSON can have
Trying to parse the JSON content from AWS SQS.
First converting a string to JSON String and then to JSON Object. What is the correct way to handle this scenario ?
<script>
// JSON from SQS
var x='{"Message":"{\"default\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
x1=JSON.stringify(x);
var obj = JSON.parse(x1);
console.log(obj.Message); // undefined
alert(obj["Message"]); // undefined
</script>
I have absolutely no idea why you are trying to JSON.stringify() a string. It's already a string!
The string you have got is not valid JSON either and needs a few extra \\s in it. Where did you get it from? Or was it a typo.
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
^__________^_____________________________________________________________^
Just parse the JSON you do have then realise that obj.Message is just more JSON that could be JSON.parse()d
// JSON
var x = '{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
//Parse JSON
var obj = JSON.parse(x);
console.log(obj.Message); // string formatted as yet more JSON
The string is not right. It should be like
var x='{"Message":"{\\\"default\\\":{\\\"key1\\\":\\\"value1\\\",\\\"key2\\\":\\\"value2\\\"}\\\"}","Timestamp":"2018-03-20T03:21:32.136Z"}';
You are stringifying the x, which is already string
x1=JSON.stringify(x); //Not ok
I would like to convert my json to a string then find and replace substrings like so using JQuery
var data = JSON.stringify(object).text();
data.text(data.replace("meat", "vegetables"));
console.log(data);
This gives me
JSON.stringify(...).text is not a function
How can I fix this.
JSON.stringify is already a text (string), that's what stringify means (turn to a string), just omit the .text():
var object = {"food":"meat","quantity":"10"}
var data = JSON.stringify(object); // this is a string
data = data.replace("meat", "vegetables");
console.log(data);
The method stringify returns string and the type string doesn't have the method text, so just update the first line to the following:
var data = JSON.stringify(object);
also update the second line with the following:
data = data.replace("meat", "vegetables");
I'm currently processing some json encoded data, but I can't access it properly, this are some tests I did:
Code fragment 1:
var json = [
{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},
{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}];
console.log(json[0][0]);
outputs:
1
Code fragment 2:
var json2 = getCookie('markers');
console.log(json2[0][0]);
outputs:
[
Code fragment 3:
console.log(getCookie('markers'));
output:
[{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}]
as you can see when I use the result from test 3 hardcoded I can access it fine, but when I use it only in code i get something diffrent
does anyone know how to do this?
Cookies only store strings. You need to use JSON.parse() to convert them back to an object. Also, the contents of json isn't JSON but a JAvaScript object (actually, an array).
var obj2 = JSON.parse(getCookie('markers') || '[]');
console.log(obj2[0][0]);
The || '[]' falls back to an empty array if the cookie is missing since an empty string or undefined wouldn't be valid JSON.
The getCookie('markers') returns string. The native javascript method JSON.parse(text[, reviver]) , parse a string as JSON.
var json2 = getCookie('markers');
if ( typeof(json2 ) == "string" ) {
json2 = JSON.parse( json2 );
}
Then try your code ..
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));