4

I want to print the Json in a nice way, I want to get rid of the brackets, quotes and braces and only use indents and line-endings to show the json's structure.

for example if I have a Json like this:

    {
        "A": {
            "A1": 1,
            "A2": 2
        },
        "B": {
            "B1": {
                "B11": {
                    "B111": 1,
                    "B112": 2
                },
                "B12": {
                    "B121": 1,
                    "B122": 2
                }
            },
            "B2": {
                "B21": [1,2],
                "B22": [1,2]
            }
        },
        "C": "CC"
    }

How could I print the json by removing {} and [], what I want is:

A:
  A1: 1
  A2: 2
B:
  B1:
     B11:
         B111: 1
         B112: 2
     B12:
         B121: 1
         B122: 2
  B2:
     B21: 1, 2
     B22: 1, 2
C: CC
yabchexu
  • 543
  • 7
  • 21

2 Answers2

7

You can load the json into a python object, and then convert the python object to YAML. The other solution is to simply iterate over the dictionaries and format it however you want.

Here's an example of converting it to YAML. It doesn't give you precisely what you want, but it's pretty close. There are lots of ways to customize the output, this is just a quick hack to show the general idea:

import json
import yaml

data = json.loads('''
   {
        "A": {
            "A1": 1,
            "A2": 2
        },
        "B": {
            "B1": {
                "B11": {
                    "B111": 1,
                    "B112": 2
                },
                "B12": {
                    "B121": 1,
                    "B122": 2
                }
            },
            "B2": {
                "B21": [1,2],
                "B22": [1,2]
            }
        },
        "C": "CC"
    }
''')

print yaml.safe_dump(data, allow_unicode=True, default_flow_style=False)

This is the output I get:

A:
  A1: 1
  A2: 2
B:
  B1:
    B11:
      B111: 1
      B112: 2
    B12:
      B121: 1
      B122: 2
  B2:
    B21:
    - 1
    - 2
    B22:
    - 1
    - 2
C: CC
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thanks Bryan, This is what I want. I have another question, is there any way I could convert Json to yaml? why I ask is because converting a python object to yaml will break the order (the key in dict) but it seems Yaml doesn't support OrderedDict. So I am thinking if I could do: python object->Json then Json->yaml in order to keep the order of the keys. – yabchexu Feb 23 '17 at 23:03
  • Yes! Thanks so much! – yabchexu Feb 24 '17 at 01:26
1

And if by chance you want it in your originally specified format, you can overload the pyyaml class structure to customize as desired:

Code:

import yaml
from yaml.emitter import Emitter
from yaml.serializer import Serializer
from yaml.representer import Representer
from yaml.resolver import Resolver

class MyRepresenter(Representer):

    def represent_sequence(self, tag, sequence, flow_style=None):
        value = []
        node = yaml.SequenceNode(tag, value, flow_style=flow_style)
        if self.alias_key is not None:
            self.represented_objects[self.alias_key] = node
        best_style = True
        for item in sequence:
            node_item = self.represent_data(item)
            if not (isinstance(node_item, yaml.ScalarNode) and 
                    not node_item.style):
                best_style = False
            value.append(node_item)
        if best_style:
            node = self.represent_data(
                str(', '.join('%s' % x.value for x in value)))
        if flow_style is None:
            if self.default_flow_style is not None:
                node.flow_style = self.default_flow_style
            else:
                node.flow_style = best_style
        return node

class MyDumper(Emitter, Serializer, MyRepresenter, Resolver):

    def __init__(self, stream,
            default_style=None, default_flow_style=None,
            canonical=None, indent=None, width=None,
            allow_unicode=None, line_break=None,
            encoding=None, explicit_start=None, explicit_end=None,
            version=None, tags=None):
        Emitter.__init__(self, stream, canonical=canonical,
                indent=indent, width=width,
                allow_unicode=allow_unicode, line_break=line_break)
        Serializer.__init__(self, encoding=encoding,
                explicit_start=explicit_start, explicit_end=explicit_end,
                version=version, tags=tags)
        MyRepresenter.__init__(self, default_style=default_style,
                default_flow_style=default_flow_style)
        Resolver.__init__(self)

print yaml.dump(data, Dumper=MyDumper, default_flow_style=False)

Produces:

A:
  A1: 1
  A2: 2
B:
  B1:
    B11:
      B111: 1
      B112: 2
    B12:
      B121: 1
      B122: 2
  B2:
    B21: 1, 2
    B22: 1, 2
C: CC
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135