-2

I'd like to consume an API (Python Django) that produce data under 'String' JSON format.

Is there an option to recognize it automatically as a JavaScript object with JQuery?

awzx
  • 1,023
  • 2
  • 12
  • 31
  • If you can use JSONP, that will solve it. https://stackoverflow.com/questions/2887209/what-are-the-differences-between-json-and-jsonp – lepe Feb 17 '18 at 07:56

3 Answers3

1

You'll want to use jQuery.parseJSON() please follow the link for full details.

I'm assuming here, that you are getting a proper JSON string.

mcgrailm
  • 17,469
  • 22
  • 83
  • 129
0

Depends on your definition of "automatically". If you mean you want the code to interpret the response as JSON without explicitly telling the code to interpret the response as JSON, then the answer is no.

What you probably want to do is abstract ajax into a function that makes the assumptions you want to make.

Goose
  • 4,764
  • 5
  • 45
  • 84
  • I meant from the API call, recognized directly as a JavaScript 'object' – awzx May 12 '17 at 09:22
  • @awzx Why not just use `JSON.parse()`? – Goose May 12 '17 at 12:57
  • JSON.parse() will throw an error if API doesn't provide JSON content – awzx May 13 '17 at 13:23
  • @awzx You can catch it like so. http://stackoverflow.com/a/4295670/3774582. You want to receive and interpret json, you have to tell the code to do so. There's nothing magical. Are you saying the api provides normal string, and you want to CONVERT it to a json? – Goose May 13 '17 at 16:06
  • In this case, JQuery.parseJSON() when receiving the data seems the safest as it'll handling the errors by itself. – awzx May 14 '17 at 15:01
  • @awzx so does parseJSON() answer your question? – Goose May 14 '17 at 15:54
  • Yes ! Among the different possible approach, that's the one I prefer. – awzx May 14 '17 at 16:00
0

if your json string as below

'{"a":0,"b":"text"}'

only with JS native

var _string = '{"a":0,"b":"text"}';
console.log(JSON.parse(_string));
alessandrio
  • 4,282
  • 2
  • 29
  • 40