-1

I have such json :

[{"pk": 1, "fields": {"name": "name 1", "description": "description 1", "image": "absolute url 1"}, "pk": 2, "fields": {"name": "name 2", "description": "description 2", "image": "absolute url 2"}}]

and i need access to fields, e.g.

$.getJSON("/json/", function(data) {
    $.each(data, function(key, value) {
        $.('#id1').append([data.pk]);
        $.('#id2').append([data.fields.name]);
5
  • Do you mean value.pk and value.fields.... Commented May 18, 2014 at 13:58
  • You need to give more information on what exactly you want to do and where you are having problems. Without that, no one can really help you. Commented May 18, 2014 at 13:58
  • 1
    The JSON is incorrect. You have duplicate pk and field properties in the same object. Commented May 18, 2014 at 14:07
  • Sorry, probably im incorrect ask a question.. i need just access to "fields" attributes (name, description,image) and pass it to DOM. Commented May 18, 2014 at 14:19
  • Guffa, those JSON returned by json.dumps (Python lib) Commented May 18, 2014 at 14:21

1 Answer 1

1

There are several errors in your code. Also your JSON is malformed.

var data = [{
    "pk": 1,
    "fields": {
        "name": "name 1",
        "description": "description 1",
        "image": "absolute url 1"
    },
    "pk": 2,
    "fields": {
        "name": "name 2",
        "description": "description 2",
        "image": "absolute url 2"
    }
}];

It has only one object with several similar properties, the last similar property overwrites the previous one, this means that the object's pk property for example is set to 2. It's probably supposed to have this structure (an array of 2 objects):

var data = [
{
    "pk": 1,
    "fields": {
        "name": "name 1",
        "description": "description 1",
        "image": "absolute url 1"
    }
}, 
{
    "pk": 2,
    "fields": {
        "name": "name 2",
        "description": "description 2",
        "image": "absolute url 2"
    }
}];

Now, you can read the objects' properties this way:

$.each(data, function (index, value) {
    console.log("pk: ", value.pk);
    console.log("fields.name: ", value.fields.name);
});

Also note that for creating a jQuery object you should remove the .:

$('#id1').append(value.pk);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! I did it with your answer, Thank you much!

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.