简体   繁体   中英

python - exporting dictionary(array) to json

I have an array of dictionaries like so:

myDict[0] = {'date':'today', 'status': 'ok'}
myDict[1] = {'date':'yesterday', 'status': 'bad'}

and I'm trying to export this array to a json file where each dictionary is its own entry. The problem is when I try to run:

dump(myDict, open("test.json", "w"))

It outputs a json file with a number prefix before each entry

{"0": {"date": "today", "status": "ok"}, "1": {"date": "yesterday", "status": "bad"} }

which apparently isn't legal json since my json parser (protovis) is giving me error messages

Any ideas? Thanks

Use a list instead of a dictionary; you probably used:

myDict = {}
myDict[0] = {...}

You should use:

myList = []
myList.append({...}

PS: It seems valid json to me anyways, but it is an object and not a list; maybe this is the reason why your parser is complaining

You should use a JSON serializer...

Also, an array of dictionaries would better serialize to something like this:

[
    {
        "date": "today",
        "status": "ok"
    },
    {
        "date": "yesterday",
        "status": "bad"
    }
]

That is, you should just use a JavaScript array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM