Undermine2k
Undermine2k

Reputation: 1491

parsing json encoded array in javascript

I am returning a json encoded object to javascript back from PHP and i wish to parse it before displaying it: However there are a few limitations.

1.I cannot refer to each individual line such as user.Relation, because if the field is empty(and it can be) I will not return it to javascript. 2. I don't know the exact fields that will be returned. 3. It is simply too large to template out even if I did know the individual fields.

when I append it to my div $('#return').append(data);

I get

{"Name":"Mike","Day Phone":"xxx-xxx-xxx","Evening Phone":"xxx-xxx-xxx","Relation":"Parent","Email":"[email protected]","Cell Phone/Pager":"xxx-xxx-xxx"}

which is technically correct, but I want something like :

Name: "Mike"
Cell Phone/Pager: "xxx-xxx-xxx"
Day Phone: "xxx-xxx-xxx"
Email: "[email protected]"
Evening Phone: "xxx-xxx-xxx"
Relation: "parent"
...

what would be my optimal(fastest) and cleanest way to parse this data out?

Upvotes: 0

Views: 89

Answers (1)

Eric H.
Eric H.

Reputation: 7014

var s = '';
for (var sAttr in json) {
  s += '<b>'+sAttr+':</b> ' + json[sAttr]+'<br/>';
}
$('#return').append(s);

Is what I would do.

Upvotes: 2

Related Questions