Ali_bean
Ali_bean

Reputation: 341

Extracting data from a JSON object

I'm trying to extract the text from this JSON return:

{
 "threaded_extended": {},
 "messages": [
    {
        "body": {
            "parsed": "the network. Take a moment to welcome Jason.",
            "plain": " network. Take a moment to welcome Jason.",
            "rich": "Jason."
        },
        "thread_id": 56,
        "client_type": "Wb",
        "client_url": "https://www.yammer.com/",
        "system_message": true,
        "direct_message": false,
        "chat_client_sequence": null,
        "language": "en",
        "notified_user_ids": [],
        "system_message_properties": {
            "subtype": "created_membership"
        },
        "privacy": "public",
        "attachments": [],
        "liked_by": {
            "count": 0,
            "names": []
        },
        "content_excerpt": " Jason.",
        "group_created_id": null
    }
]

} my function looks like this, but it keeps saying undefined - sorry if this is a dumb question, my logic is that the object is value, then messages is an attribute, and then plain should be an attribute of that. Am I doing something stupid? Appreciate any help

function getData(returnData){
    $.each(returnData, function(key, value){
        if(value != undefined){
            $('#test').append(value.messages.plain);
        }
    });
}

Upvotes: 0

Views: 84

Answers (2)

dogant
dogant

Reputation: 1386

 $('#test').append(value.messages[0].plain);

messages is an array so you need to provide an index.


Edit : I thought returnData was an array, if it's not the case you're looping on the wrong object. Loop through returnData.messages. and get value.body.plain

Upvotes: 2

Alina Mihai
Alina Mihai

Reputation: 26

Iterate through returnData.messages the array in your object. Then you can access each message item in the array, whereas the plain value is on body.plain for each value

function getData(returnData){
    $.each(returnData.messages, function(key, value){
        if(value != undefined){
            $('#test').append(value.body.plain);
        }
    });
}

Upvotes: 1

Related Questions