Walter U.
Walter U.

Reputation: 341

Python: turn JSON object to JSON array

I have the following dictionary in python which I'm saving into a file:

d2 = {
    "CHARACTER": {
        "IDENTITY": {
            "FORM": {
                "id": "BK1",
                "type": "MAGE",
                "role": "DARK"
            }
        },
        "USER": {
            "owner": {
                "id": "SABBATH13"
            },
            "level": "16"
        }
    }
}

jsonfile = open('d2.json', 'w')
jsonfile.write(simplejson.dumps(d2, indent=4))
jsonfile.close()

However, I'm told this is a JSON object, which I need to turn into a JSON array of the form:

[{
    "CHARACTER": {
        "IDENTITY": {
            "FORM": {
                "id": "BK1",
                "type": "MAGE",
                "role": "DARK"
            }
        },
        "USER": {
            "owner": {
                "id": "SABBATH13"
            },
            "level": "16"
        }
    }
}]

Which is essentially adding square brackets at the beginning and end.

What is the proper way to do this? Should I convert to string and add brackets, then convert back? Sorry, total JSON newbie here.

Upvotes: 1

Views: 5537

Answers (1)

deceze
deceze

Reputation: 522032

You're thinking at the wrong level of abstraction. It's not about the brackets, it's about that you have a data structure which is an object, when what you apparently need is a list/array of objects (even if there's just one object in the list). So:

d2 = [d2]

Now dumps this and you get what you need.

Upvotes: 5

Related Questions