简体   繁体   中英

Parse JSON with JavaScript to build a HTML string

I currently have built an API which posts JSON strings of objects. A simple example of the JSON is:

[ {
  "id" : 0,
  "name" : "test SAMPLE Att1 name",
  "attributes" : [ {
    "id" : -1,
    "name" : "AttKey1",
    "value" : "AttValue1"
  }, {
    "id" : -1,
    "name" : "AttKey2",
    "value" : "AttValue2"
  } ]
} ]

My issue lies in my client code here:

function loadSamples() {
  $("#content").children().remove();
  $.getJSON("/api/samples", function (data) {
    $.each(data, function (key, val) {
      $("<tr><td>" + val.id + "</td><td>" + val.name + "</td><td>" + val.attributes + "</td>" +
        "</tr>").appendTo("#content");
    });
    initCallbacks();
  });
}

I am iterating through each sample I send (in this case only one, and appending the field values to the HTML string. How can I iterate through attributes and append each attribute.key and attribute.value to the string?

A picture of the current problem:

在此处输入图片说明

Use another loop, iterate through all attributes, build an array of attributes in format "property: value" and then append joined array to HTML:

$.each(data, function (key, val) {
  var attributes = [];
  for (var prop in val.attributes) {
    var value = val.attributes[prop];
    attributes.push(prop + ": " + value);
  }
  $("<tr><td>" + val.id + "</td><td>" + val.name +
    "</td><td>" + attributes.join(",") + "</td>" + "</tr>").appendTo("#content");
});

If you feel nerdy you can just serialize the object back into a JSON string like this:

... + JSON.stringify(val.attributes) + ...

It is recursive, has a standard syntax (JSON) and doesn't require any support function or additional code at all.

You can try to use this code instead of val.attributes

$.map(val.attributes, function(item){
   return item.key + ':' +item.value;
}).join(',')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM