0

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.

3
  • 2
    JSON.parse(JSON.stringify(data)); this does exactly... Nothing. Remove the stringify. Commented Jun 26, 2016 at 3:57
  • 1
    What do you think JSON.stringify does? The steps to debug this would be to log the value return by JSON.stringify(data) and returned by JSON.parse(JSON.stringify(data));. Then you probably would have already found out why it doesn't work. Commented Jun 26, 2016 at 4:03
  • If you stringify JSON you have to parse a parsed result and would need to do var obj = JSON.parse((JSON.parse(JSON.stringify(data))); ... what's wrong with this picture? Commented Jun 26, 2016 at 4:09

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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']);
}

2 Comments

"I your example, data is a string, not JSON" uhm, data is a string containing JSON. Are you confusing "JSON" with JavaScript values / objects?
"data is a string, not JSON" ... huh? what do you think JSON is by defintion?
0

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']);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.