Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- try:
- basestring
- except NameError:
- basestring = str
- def pretty_print_json(jdata):
- buf = []
- _pp_dict(jdata, 0, buf)
- return "".join(buf)
- def _pp_dict(dct, depth, buf):
- space = " " * depth
- buf.append('{\n')
- for k, v in dct.items():
- buf.append('%s "%s": ' % (space, k)) # TODO: escape k
- if isinstance(v, list):
- _pp_list(v, depth+1, buf)
- elif isinstance(v, dict):
- _pp_dict(v, depth+1, buf)
- else:
- _pp_scalar(v, depth+1, buf)
- buf.append(',\n')
- if buf[-1] == ',\n':
- buf.pop()
- buf.append('\n')
- buf.append(space)
- buf.append('}')
- def _pp_list(lst, depth, buf):
- space = " " * depth
- buf.append('[\n')
- for x in lst:
- buf.append(space)
- if isinstance(x, list):
- _pp_list(x, depth+1, buf)
- elif isinstance(x, dict):
- buf.append(' ')
- _pp_dict(x, depth+1, buf)
- else:
- _pp_scalar(x, depth+1, buf)
- buf.append(',\n')
- if buf[-1] == ',\n':
- buf.pop()
- buf.append('\n')
- buf.append(space)
- buf.append(']')
- def _pp_scalar(scalar, depth, buf):
- buf.append(_repr_scalar(scalar))
- def _repr_scalar(scalar):
- if scalar is None:
- return "null"
- elif scalar is True:
- return "true"
- if scalar is False:
- return "false"
- if isinstance(scalar, basestring):
- return '"%s"' % scalar.replace('"', r'\"')
- if isinstance(scalar, (int, float)):
- return str(scalar)
- raise TypeError("%r: unknown data type" % (scalar,))
- if __name__ == '__main__':
- jdata = {
- "books": [
- {
- "id": 101,
- "title": u"すごい本",
- "authors": [
- {
- "id": 2001,
- "name": u"著者1"
- },
- {
- "id": 2001,
- "name": u"著者2"
- }
- ]
- },
- {
- "id": 102,
- "title": u"もっとすごい本",
- "authors": [
- {
- "id": 2103,
- "name": u"著者3"
- }
- ]
- }
- ]
- }
- s = pretty_print_json(jdata)
- print(s.encode('utf-8'))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement