0

How to use foreach parse the json type -

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {
            
            $(dataid).html(data);
        });
    }

data = {"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"}

I would get text -

1 - Hello World - Jenan - 1 - url.

2 Answers 2

2

for...in will loop through each object key:

var output = [];
for( var key in data) {
  if (data.hasOwnProperty(key)) {
      output.push(data[key])
  }
}

alert(output.join(' - '));


EDIT

data.url; // the value of url, which happens to be url in this example
// or
data['url']

hasOwnProperty ensures that the key is a direct property of the object.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for suggesting Array.join. It's simpler, and more efficient than string concatenation.
1

The $.each() function only works on Arrays and jQuery objects.

Here, data is not an array, its a regular object.

So, get the data from your Json this way :

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {
            $(dataid).html(data.file +' - '+ data.text +' - '+ data.name +' - '+ data.id +' - '+ data.url);
        });
    }

EDIT: If you have some of these objects in an Array like the one that follows :

[{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"},{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"},{"file":"1","text":"Hello world","name":"Jenan","id":"1","url":"url"}]

Do like that :

getData: function(id, dataid)
    {
        $.post('Action/Load.php',{
            id: id
        }, function(data) {
            $(dataid).html('');
            $.each(data, function(key, value){
                $(dataid).append(value.file +' - '+ value.text +' - '+ value.name +' - '+ value.id +' - '+ value.url +'<br/>');
            });
        });
    }

5 Comments

And if I had a collection of data. How can I read only the url?
What do you mean by a collection of data ? Show me the Json representation of what you have in mind
I try your example and this is result - undefined - undefined - undefined - undefined - undefined
For example this collection : [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ]
alright, then you need a $.each(), try with the updated code

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.