0

Using $.ajax i'm calling for a json data. server returns me json within () like:

({
  "FileCount": 3,
  "Files": [{},{}]
});

How should I parse or extract the data from it? Thanks

  • 9
    This isn't valid JSON even with `(` and `)` removed. The keys need to be in double quotes. You should fix your source to produce valid JSON, rather than try to guess how to fix the invalid one. – VLAZ May 13 '21 at 10:50
  • **after edit** Other than fix your source, you can remove the `()` and parse it normally. Which bit are you having difficulty with? Removing the `()`? Parsing a string to an object? – freedomn-m May 13 '21 at 11:07
  • Does this answer your question: https://stackoverflow.com/questions/4935632/parse-json-in-javascript (found by searching for `JavaScript parse (JSON)`) – freedomn-m May 13 '21 at 11:21
  • @freedomn-m doesn't jQuery automatically parse the JSON? – evolutionxbox May 13 '21 at 11:22
  • 1
    @evolutionxbox It can't parse it automatically because the server response isn't valid JSON. – Thomas Sablik May 13 '21 at 11:30
  • I don't have any problem to remove (). I thought that it's some special to jQuery format so I asked people about that. – Andrey Serdyuk May 13 '21 at 11:32
  • 1
    @evolutionxbox depends on the `dataType` option. See [here](https://api.jquery.com/jquery.ajax/). If you set it to "JSON" it will do the parsing for you and hand you the result. If you set it to "text" you'd get the string result. By default it does an intelligent guess. That depends on what data you get as well as what [`Conent-Type` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) is set. For example, if the MIME type given is `text/plain` jQuery will not try to parse that response. There is also `converters` option for jQuery to override the parser. – VLAZ May 13 '21 at 11:46

1 Answers1

0

I got what is going on with such a JSON response! There was supposed to be a callback which received the JSON. Since the callback is a function the response was sorrounded with (). But the callback wasn't provided so, instead of callback({}) I get ({})