1

I am getting JSON data from server, I have always confusion about this, How I will know that, fetched data is json string or json object. I have asked two questions but both are related.

{"series": [{"meter": "instance", "data": [{"y": 82.0, "x": "2015-07-14T23:58:00"}, {"y": 142.0, "x": "2015-07-15T23:58:10"}, {"y": 144.0, "x": "2015-07-16T23:58:10"}, {"y": 139.0, "x": "2015-07-17T23:56:17"}, {"y": 144.0, "x": "2015-07-18T23:56:18"}, {"y": 144.0, "x": "2015-07-19T23:56:17"}, {"y": 277.0, "x": "2015-07-20T23:50:09"}, {"y": 294.0, "x": "2015-07-21T23:51:34"}, {"y": 135.0, "x": "2015-07-22T07:21:34"}], "name": "demo", "unit": "instance"}], "settings": {}}

If above is JSON object or JSON string then how will I convert into each other?

galath
  • 5,717
  • 10
  • 29
  • 41
geeks
  • 2,025
  • 6
  • 31
  • 49

2 Answers2

2

One way is to check the response header content-type: application/json which will give what content type it is.

string to json-> JSON.parse(str); json to String -> JSON.stringify(jsonObj);

abs
  • 801
  • 6
  • 15
  • thanks for the `content-type: application/json` I is showing like Content-Type=application/json, But Is is json object or Json string... – geeks Jul 22 '15 at 10:16
  • if content type is application/json then it is an json object. for string it would be text/html – abs Jul 22 '15 at 14:50
1

HTTP can only work with string type data in fact, and you need to format the responsed data string according to the http response header which the field name is Content-Type, and json value is application/json.

That means, the value is always a string, but there's another variable(Content-Type) to record it's type format.

Allen
  • 6,745
  • 5
  • 41
  • 59