当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Get a certain value from a json object

问题描述:

I have a json object

eg

{

"href":"Test",

"commentID":"12334556778"

}

Is there a way just to get the second line i.e. "commentID":"12334556778"

I'm using

JSON.stringify(json)

Thanks all

网友答案:

JSON.stringify accepts a third argument which handles white-space in the output. If the third argument is present and "truthy", line-breaks will be inserted and each level will be indented using the argument's string value, or a number of spaces if a number is passed. Using this technique, you can get the browser to insert line-breaks and then split on those line-breaks in the result:

var obj = {
        "href":"Test",
        "commentID":"12334556778"
    },
    arr = JSON.stringify(obj, null, 1).split("\n");

alert(arr[2]);
//-> ' "commentID": "12334556778"'

Working demo: http://jsfiddle.net/AndyE/ercRS/ (requires browsers with JSON/trim)

You might want to trim any leading white space or trailing comma, but I'll leave that up to you.

网友答案:

You can create another object containing only the commentID property:

var obj = {
    "href": "Test",
    "commentID": "12334556778"
};

var result = JSON.stringify({
    "commentID": obj.commentID
});
网友答案:

if you have a JSON object at hand, just use it like you would use an array.

var jsonObject = {
   "href":"Test",
   "commentID":"12334556778"
}
alert(jsonObject['commentID']); // alerts 123445678

JSON.stringify() is used if you want to send the data back to your server.

分享给朋友:
您可能感兴趣的文章:
随机阅读: