JSON-如何从json字符串中获取单个内容

时间:2016-09-06 06:12:37

标签: javascript jquery json

我将数据检索为像

这样的JSON字符串
var jsonPretty = JSON.stringify(data, null, 2);

{
    "GetPageInfoResult": [{
        "main": {
            "sub": [],
            "tittle": "hllo",
            "startvalue": "21",
            "stopvalue": "45",
            "status": "",
            "accumalated": "",
            "comment": ""
        }
    }]
}

如何将我的专栏内容设为:

$("tr[data-id=1] > td:nth-child(1)").text(hllo)

$("tr[data-id=1] > td:nth-child(2)").text(21)

$("tr[data-id=1] > td:nth-child(3)").text(45)

2 个答案:

答案 0 :(得分:1)

像这样:https://jsfiddle.net/d5qe70bw/

var mr_cools_data = [{
    "main": {
        "sub": [],
        "tittle": "water",
        "start value": "21",
        "stop value": "45",
        "status": "",
        "accumulated": "",
        "comment": ""
    }
}]

$("tr[data-id=1] > td:nth-child(1)").text(mr_cools_data[0].main['tittle'])

$("tr[data-id=1] > td:nth-child(2)").text(mr_cools_data[0].main['start value'])

$("tr[data-id=1] > td:nth-child(3)").text(mr_cools_data[0].main['stop value'])

另外,考虑从json中删除[],它将'main'对象包装在一个对这个数据似乎无用的数组中。另外,建议不使用空格命名属性(将start value更改为start_value

答案 1 :(得分:1)



var jsonPretty  = [{
    "main": {
        "sub": [],
         "tittle": "hllo",
            "startvalue": "",
            "stopvalue": "",
            "status": "",
            "accumalated": "",
            "comment": ""
    }
}]

$("tr[data-id=1] > td:nth-child(1)").text(jsonPretty [0].main['tittle']);

$("tr[data-id=1] > td:nth-child(2)").text(jsonPretty [0].main['start value']);

$("tr[data-id=1] > td:nth-child(3)").text(jsonPretty [0].main['stop value']);

$("tr[data-id=1] > td:nth-child(4)").text(jsonPretty [0].main['status']);

$("tr[data-id=1] > td:nth-child(5)").text(jsonPretty [0].main['accumulated']);

$("tr[data-id=1] > td:nth-child(6)").text(jsonPretty [0].main['comment']);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr data-id="1">
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>
&#13;
&#13;
&#13;

这可能会帮助你。