Jake
Jake

Reputation: 1491

Styling JSON pages

I'm working on a JSON API and I want to do something like Facebook's opengraph styling. The opengraph style indents and breaks lines, how do you go about doing this? If you use styling through HTML or CSS the JSON can not be loaded.

Upvotes: 0

Views: 377

Answers (2)

andrew cooke
andrew cooke

Reputation: 46862

facebook appear to be using browser detection to format the JSON on the server.

for wget, no formatting is applied:

> wget -q -S -O - http://graph.facebook.com/4
  HTTP/1.1 200 OK
  Access-Control-Allow-Origin: *
  Cache-Control: private, no-cache, no-store, must-revalidate
  Content-Type: text/javascript; charset=UTF-8
  ETag: "539feb8aee5c3d20a2ebacd02db380b27243b255"
  Expires: Sat, 01 Jan 2000 00:00:00 GMT
  P3P: CP="Facebook does not have a P3P policy. Learn why here: http://fb.me/p3p"
  Pragma: no-cache
  X-FB-Rev: 526949
  Set-Cookie: datr=imJrT4lrhBZ48Mrtw4uYfByk; expires=Sat, 22-Mar-2014 17:34:02 GMT; path=/; domain=.facebook.com; httponly
  X-FB-Debug: +gpBLnliDoRvuNtlHIwHASwsDz4pJm9TP3btrrw6AsE=
  X-Cnection: close
  Date: Thu, 22 Mar 2012 17:34:02 GMT
  Content-Length: 172
{"id":"4","name":"Mark Zuckerberg","first_name":"Mark","last_name":"Zuckerberg","link":"http:\/\/www.facebook.com\/zuck","username":"zuck","gender":"male","locale":"en_US"}

but for google chrome, wireshark shows text formatted with spaces and newlines:

{
   "id": "4",
   "name": "Mark Zuckerberg",
   "first_name": "Mark",
   "last_name": "Zuckerberg",
   "link": "http://www.facebook.com/zuck",
   "username": "zuck",
   "gender": "male",
   "locale": "en_US"
}

(it really is different data - the Content-Length is 210 in this case). note that Content-Type is still text/javascript - they are not rendering into HTML.

so you'd need to use a JSON formatter for whatever language you are using (i guess you are already using a library, so check whether it has a "prettyprint" option or similar). plus, if you want to save bandwidth when formatting seems unimportant, browser (and general context - see Paul's comment) detection from request headers.

Upvotes: 3

Paul
Paul

Reputation: 141829

You can use JSON_PRETTY_PRINT which is new in PHP 5.4:

<?php 

// Facebook sends a Content-Type of text/javascript
// So I assume you want to too, but you may prefer
// application/json
header('Content-Type: text/javascript');

echo json_encode($data, JSON_PRETTY_PRINT);

?>

If you don't have, or can't upgrade to version 5.4 then you have to find some side of server-side parser.

Edit

I don't know why I assumed you're using PHP when you haven't tagged it. Whatever server side language you're using though you'll want to send out a non-html Content-Type and use new lines and tabs to pretty print it, not HTML.

Upvotes: 3

Related Questions