1

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.

AntoineLB
  • 482
  • 3
  • 19
Walter U.
  • 331
  • 1
  • 7
  • 18

1 Answers1

5

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks, this works, though I tried something similar and got: `ValueError: dictionary update sequence element #0 has length 9; 2 is required` – Walter U. May 01 '18 at 12:25