Search code examples
pythonjsonstring-formatting

how to format json dumps


I got json dumps like this:

"aaa": {
    "bbb": {
        "ccc": {
            "ddd": "string1",
            "eee": "string2"
        }
    },
    "kkk": "string3"
}

And I'd like to format it this way: enclose every key-value pair (separated by :) with {} and then replace : with ,.

I know that I can use re.sub() to replace string patterns, but regular expression does not work with overlapping patterns, so I can match, for example, "ddd": "string1" but not "ccc": {...} at the same time.

For the above json string, I'd like to get:

{"aaa", {
    {"bbb", {
        {"ccc", {
            {"ddd", "string1"},
            {"eee", "string2"}
        }}
    }},
    {"kkk", "string3"}
}}

Solution

  • Here's a hack which converts everything to lists and then changes square brackets to curly ones. If your strings might contain square brackets that'll be a problem.

    import json
    
    inp = """
    {
        "aaa": {
            "bbb": {
                "ccc": {
                    "ddd": "string1",
                    "eee": "string2"
                }
            },
            "kkk": "string3"
        }
    }
    """
    
    inp = json.loads(inp)
    
    
    def items(d):
        if isinstance(d, dict):
            return [(k, items(v)) for k, v in d.items()]
        return d
    
    
    inp = items(inp)
    
    print(json.dumps(inp, indent=2).replace("[", "{").replace("]", "}"))
    

    Output:

    {
      {
        "aaa",
        {
          {
            "bbb",
            {
              {
                "ccc",
                {
                  {
                    "ddd",
                    "string1"
                  },
                  {
                    "eee",
                    "string2"
                  }
                }
              }
            }
          },
          {
            "kkk",
            "string3"
          }
        }
      }
    }