-1

I have a JSON response data as follows

{"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }

How can I fetch only the data array using jquery?

Showing error as parsererror; SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 666 of the JSON data in console while parse/stringify

Hulk1991
  • 3,079
  • 13
  • 31
  • 46

4 Answers4

4

Use dot notation

var obj = {"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }

console.log(obj.data);

https://jsfiddle.net/c8z35au4/

or parse the data

var unparsed = '{"response":"9",
     "status":"Success",
     "msg":"Valid Access",
     "data":[{"id":"1","title":"A"},
            {"id":"2","title":"B"},
            {"id":"3","title":"C"}]
     }';
var obj = JSON.stringify(unparsed);
console.log(obj.data);
madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • 2
    @Vinod That probably means you haven't parsed the JSON string and the string object doesn't have `data` property. – Ram Apr 27 '16 at 10:24
3

If it's Ajax request:

$.ajax({
    dataType: 'json',
    success: function (response) {
        console.log(response.data);
    }
});

If it's string, than use var response = JSON.parse(string) and response.data

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • `parsererror; SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 666 of the JSON data` – Hulk1991 Apr 27 '16 at 10:26
  • @Vinod This error means that your JSON response contains more than JSON. Like `{id: 5}(int)5`. Clean your JSON first than – Justinas Apr 27 '16 at 10:27
  • I got response from `http://www.vtc.com/services/api/restApiClient/?task=getAllCategories` – Hulk1991 Apr 27 '16 at 10:29
2

var data = {"response":"9",
 "status":"Success",
 "msg":"Valid Access",
 "data":[{"id":"1","title":"A"},
        {"id":"2","title":"B"},
        {"id":"3","title":"C"}]
 }
 
 
 
 console.log(JSON.stringify(data.data))
guradio
  • 15,524
  • 4
  • 36
  • 57
-1

The best way is

 var data = {"response":"9",
     "status":"Success",
     "msg":"Valid Access",
     "data":[{"id":"1","title":"A"},
            {"id":"2","title":"B"},
            {"id":"3","title":"C"}]
     }

    data=JSON.parse(data);
   var requiredData=data.data;
   for(var i in requiredData)
{
     var id = requiredData[i].id;
     var title = requiredData[i].title;
     console.log(id);
     console.log(title);

}
Deepak Mani
  • 125
  • 11