Reputation: 107
Right now I am getting my JSON url response as I would like to pretty print this URL
[{"chat":"ed test","displayname":"Ed Student","created_at":"2014-03-29 21:42:35"},
{"chat":"test from sue","displayname":"Sue Student","created_at":"2014-03-29 21:42:25"},{"chat":"Test from instructor","displayname":"Jane Instructor","created_at":"2014-03-29 21:42:18"}]
but I would like to get it to look like this:
[
{
"chat":"ed test",
"displayname":"Ed Student",
"created_at":"2014-03-29 21:42:35"},
{
"chat":"test from sue",
"displayname":"Sue Student",
}
]
and so on.
My code is following:
$.ajax({
type: "POST",
url: "chatlist.php?PHPSESSID=9c2b21f6309fd0cb8c157b54eafb7381",
cache: true,
async: true,
dataType:"json",
data: JSON.stringify(messages, null, 4),
success: function(data){
$("#messages").empty();
for (var i = 0; i < data.length; i++) {
entry = data[i];
$("#messages").append("<p>"+htmlentities(entry.chat)+'<br/> '
+htmlentities(entry.displayname)+' '+htmlentities(entry.created_at)+"</p>\n");
console.log(JSON.stringify(data[i]));
}
OLD_TIMEOUT = setTimeout('messages()', 4000);
}
});
Is it possible to format the response URL that I am getting with this $.ajax call?
Upvotes: 2
Views: 167
Reputation: 1539
jq
is a command line json processor. you can use jq
also for formatting json. when you saved your ajax call responses as json files then jq
is the best way to format it on command line.
example:
$ echo '{ "foo": "lorem", "bar": "ipsum" }' | jq .
{
"bar": "ipsum",
"foo": "lorem"
}
see jq
homepage with tutorials: http://stedolan.github.io/jq/
see also the similar SO question: How can I pretty-print JSON in (unix) shell script?
Upvotes: -1
Reputation: 107
In my PHP code I had
echo(json_encode($messages));
When I should have had
echo(json_encode($messages, JSON_PRETTY_PRINT));
Which was printing out my JSON.
Upvotes: 1
Reputation: 15742
I think you are looking for,
JSON.stringify(value[, replacer [, space]])
Like,
var data = JSON.stringify(data, null, "\t"); // Using a tab character mimics standard pretty-print appearance
console.log(data);
Check
Read:
Upvotes: 2