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.

2
  • stackoverflow.com/questions/26745519/… have a look here to see if this helps? Commented May 1, 2018 at 12:21
  • cant you do jsonfile.write(simplejson.dumps([d2], indent=4)? Commented May 1, 2018 at 12:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works, though I tried something similar and got: ValueError: dictionary update sequence element #0 has length 9; 2 is required

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.