输出JSON键,JavaScript中的值 [英] Output JSON key, value in JavaScript

查看:57
本文介绍了输出JSON键,JavaScript中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json文件,其内容格式如下:

I have a json file with content in this format:

{
  "Florida":{
   "4079823456" : "Text message content 1 here",
   "4079323457" : "Text message content 2 here",
   "4079823458" : "Text message content 3 here"
},

"Texas":{
   "2149823456" : "Text message content 1 here",
   "2149323457" : "Text message content 2 here",
   "2149823458" : "Text message content 3 here"
}

}

我正在使用javascript(无库)将json文件中的键/值对输出到html表以获取如下输出:

I am using javascript (no libraries) to output the key/value pairs in the json file to an html table to get an output like this:

Phone Number | Text Message
4079823456   | Text message content 1 here
4079323457   | Text message content 2 here

但是,相反,我得到了这样的东西:

But instead, I get something like this:

  Phone Number | Text Message
      0            {
      1            "

以下是我的javascript的代码段:

The following is a code snippet from my javascript:

var str = JSON.stringify(http_request.responseText);
var obj = JSON.parse(str);
var rowContent;

var tablerows = document.getElementById("tablerow");

for(var key in obj){
   rowContent = "<tr><td>" + key + "</td><td>" + obj[key] + "</td></tr>";

   tablerows.innerHTML += rowContent;
}

如何获取键值对以输出到所需的输出,而不是获取JSON文件中的每个字符?理想情况下,我想遍历键和值(在我的情况下是电话号码和短信),因为实际上有数百个.

How can I get the key value pairs to output to the desired output instead of getting each individual character in my JSON file? Ideally, I would like to loop through both the key and the value (in my case, the phone numbers and text messages) as there are actually hundreds of them.

谢谢.

推荐答案

对于您的数据,您可以使用两个for...in循环并添加到table中.创建带有表内容的字符串并在循环结束后添加它也是更好的选择.

For your data you can use two for...in loops and add to table. Also its better to create string with table content and add it after loop is finished.

var data = {
  "Florida": {
    "4079823456": "Text message content 1 here",
    "4079323457": "Text message content 2 here",
    "4079823458": "Text message content 3 here"
  },
  "Texas": {
    "2149823456": "Text message content 1 here",
    "2149323457": "Text message content 2 here",
    "2149823458": "Text message content 3 here"
  }
}

var table = document.querySelector('table');
var rows = '';
for (var p in data) {
  for (var k in data[p]) {
    rows += '<tr><td>' + k + '</td><td>' + data[p][k] + '</td></tr>'
  }
}
table.innerHTML = rows;

<table></table>

这篇关于输出JSON键,JavaScript中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆