geoffreyGIS
geoffreyGIS

Reputation: 363

How to remove brackets from JSON in Python?

I am using json.dumps to load lists of dictionaries into a JSON object. My output resembles this:

[
    {
        "MetaData": {},
        "SRData": {
            "ListOfLa311DeadAnimalRemoval": {
                "DeadAnimalRemoval": [
                    {
                        "DACItemCount": "0",
                        "DACType": " ",
                        "DriverFirstName": "SA",
                        "DriverLastName": "Aguilar",
                        "LastUpdatedBy": "SANSTAR1",
                        "Name": "070920151119458601",
                        "Type": "Dead Animal Removal"
                    },
                    {
                        "DACType": " ",
                        "DriverFirstName": "SA",
                        "DriverLastName": "Aguilar",
                        "LastUpdatedBy": "SANSTAR1",
                        "Type": "Dead Animal Removal"
                    }
                ]
            },
            "ReasonCode": "",
            "ResolutionCode": "A",
            "SRNumber": "1-20979881"
        }
    }
]

How do I successfully remove the brackets at the beginning and end of the JSON object?

Code that appends dictionaries and lists:

    dL311 = dict()
    dL311.setdefault("DeadAnimalRemoval", l311)
    dResult.setdefault("ListOfLa311DeadAnimalRemoval",dL311)

    #Ends of adding additional itmes ****************************************
    lResults.append({"MetaData": {}, "SRData": dResult})

    ii = ii + 1
    print(json.dumps(lResults, sort_keys=True, indent=4))

Upvotes: 4

Views: 35279

Answers (2)

Vortico
Vortico

Reputation: 2749

The brackets denote a JSON array, containing one element in your example. In Python, simply pick out the first element of the root array and convert back to JSON.

import json
data = json.loads('[...]')
str = json.dumps(data[0])

Upvotes: 4

alecxe
alecxe

Reputation: 473873

Just serialize the dictionary:

result = {"MetaData": {}, "SRData": dResult}
print(json.dumps(result, sort_keys=True, indent=4))

Upvotes: 2

Related Questions