skip to Main Content

I’m relatively new to working with JSON and am trying to output a dictionary to JSON using the json library in python. The issue I have is the format is very specific and I’m not sure how to approach. Specifically the desired format has extra braces and brackets. Below is an example of the dictionary I’m converting to JSON and the desired output:

    #Sample Data
sample_dict = {"office":{"50":"pencil;paper",
                      "100":"stapler;eraser"},
             "warehouse":{"50":"forklift;wrench",
                         "100":"truck,screw"}}

with open('test.json', 'w') as f:
    json.dump(sample_dict, f,indent = 4)

##Output I'm able to acheive
{
    "office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    },
    "warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }
}


##Desired Output
[{
    {"office": {
        "50": "pencil;paper",
        "100": "stapler;eraser"
    }},
    {"warehouse": {
        "50": "forklift;wrench",
        "100": "truck,screw"
    }}
}]

2

Answers


  1. I think you need to make the “sample_dict” a string with square brackets.

    import json
    
    sample_dict = '[{"office":{"50":"pencil;paper", "100":"stapler;eraser"}, "warehouse":{"50":"forklift;wrench", "100":"truck,screw"}}]'
    
    load=json.loads(sample_dict)
    print(json.dumps(load, indent=4))
    

    Output

    Login or Signup to reply.
  2. The extra [] would be easy — the whole dictionary is in a list. However, the extra {} are not; the sample you posted is not, in fact, valid JSON.

    At this point, you’ll need to clarify whether the output should be JSON or whether it should match the given sample.

    • If the output should be JSON, you’ll need to get a correct sample output, then work from there. At a minimum, the top level is a list of dictionaries.

    • If the output should match the given sample, it’s not JSON and you won’t be using the json library. Depending on the situation, you can:

      • format it up with Python string formatting (% or .format() or f"..." strings); or
      • use a templating library like Jinja or Mako or similar; or
      • if the data structure is extensive and the format is consistent, write your own library for outputting that format.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search