Reputation: 8285
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
Upvotes: 1
Views: 324
Reputation: 1585
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.
Upvotes: 0
Reputation: 344527
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.
Upvotes: 1
Reputation: 262919
You can create another object containing only the commentID
property:
var obj = {
"href": "Test",
"commentID": "12334556778"
};
var result = JSON.stringify({
"commentID": obj.commentID
});
Upvotes: 2