1

Im using Django, the view that returns json object, has the next code:

def searchTourDBEsp_view(request):
    print 'llamamos search ESP'
    dataTourEsp = TourEsp.objects.raw('SELECT * FROM appMain_tour where idTour=1')
    dataTourEspSer = serializers.serialize("json",dataTourEsp)
    return HttpResponse(json.dumps(dataTourEspSer),content_type='application/json')

as you can see i have to make a serialization to the database consult.

In my template i need to have access to the data that is returned.

$.ajax({
         type:"POST",
         url:  '{% url "url_searchTourEsp"%}',
         data: data1,             
         success: function(jsonAjaxResult){  
                  console.log("Ajax ok");
                  console.log("nombre");
                  console.log(jsonAjaxResult);   
                  console.log(jsonAjaxResult[0]);  
                                },
                  error: function(data){
                   alert("Got an error, Pleas conctact the Administrator");
                   alert(data);
            }
});

The jsonAjaxResult object has all the information that i need, but it is an array of string. The content of jsonAjaxResult is the follow

[{
"fields":
 {
 "Monday": true, 
 "restrictions": "No kids",
 "name": "Yate Mar", 

 }, 
 "model": "appMain.touresp", 
 "pk": 1
 }]

and the only way to have access to the data is typing

console.log(jsonAjaxResult[0]); 

that has as result [

does someone know how to have access to the information like:

jsonAjaxResult['restrictions'];

but if i type this, the result is undefined

2
  • jsonAjaxResult[0]['restrictions'] You need to iterate over the array and query the restriction of each element. Commented Dec 14, 2015 at 3:46
  • if i write console.log(jsonAjaxResult[0]['restrictions']); the result is undefined Commented Dec 14, 2015 at 4:08

1 Answer 1

1

To reference a particular index in an array, the syntax is array[index]. To reference an object's property, the syntax is object.property or object["property"]. Since your data structure involves nested objects within an array, simply use the appropriate syntax for referencing the value at each layer.

In this case, your top-level data type is an array. That array contains an object with a property named fields. The value of that property is, in turn, another object that has its own property named restrictions. You have to reference each of these from the top-down.

var data = [
    {
        "fields": {
            "Monday": true, 
            "restrictions": "No kids",
            "name": "Yate Mar",
        }, 
        "model": "appMain.touresp", 
        "pk": 1
    }
];

To get the value for the restrictions property, do the following: data[0].fields.restrictions.

If your array has multiple values and you wish to get the restrictions for each one, iterate over the array and substitute the 0 with your array index variable. That is:

for (var i=0; i < data.length; i++) {
    console.log(data[i].fields.restrictions);
}


EDIT: You'll have to decode your JSON string into an array before doing this. Use JSON.parse for that:

JSON.parse(jsonAjaxResult)[0].fields.restrictions
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for you help, i did what you tould me, but the next error shows up : Uncaught TypeError: Cannot read property 'restrictions' of undefined The jsonAjaxResult is an array of String because if i type jsonAjaxResult[0] the result is '[' and if you iterate over that array it shows '{' , '"' , 'f' , 'i' , 'e' , ........
@Matvi That seems to suggest the actual structure of the data is a little different than what you've posted. Can you do a console.log(jsonAjaxResult) and post what gets logged to the console? It could be that the data was not properly JSON-serialized.
@Matvi Oh got it. You don't have an array of strings. You just have a single string, because your data hasn't been decoded and it's wrapped as a string. You'll have to parse the JSON before accessing the data. See update above.

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.