Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 633
geoffreyGIS Avatar asked Oct 15 '25 19:10

geoffreyGIS


2 Answers

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])
like image 75
Vortico Avatar answered Oct 18 '25 07:10

Vortico


Just serialize the dictionary:

result = {"MetaData": {}, "SRData": dResult}
print(json.dumps(result, sort_keys=True, indent=4))
like image 40
alecxe Avatar answered Oct 18 '25 07:10

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!