简体   繁体   中英

How can I format my Python dictionary to match the below JSON format using json.dumps()

I am using python to complete some scripting tasks and I have to send some data to another program using my scripts stdout. In order to communicate, I have a set example of how the JSON needs to be formatted but I am struggling to replicate the format:

{
  "Bookmarks": [{
    "BookmarkPath": "path/foo/bar",
    "HtmlColor": "#7FCC99",
    "Comment": "AAA",
    "Sha1": "xxx"
  }]
}

My code is using the standard json library and the method .dumps to take my dictionary that looks like:

dict = {
    'Bookmarks':{
        'BookmarkPath': "path/foo/bar",
        'HtmlColor': "#7FCC99",
        'Comment': "AAA",
        'Sha1': "xxx"
    }
}

Ultimately it's formatting as such, which doesn't work:

{
"Bookmarks": {
    "BookmarkPath": "path/foo/bar",
    "HtmlColor": "#7FCC99",
    "Comment": "AAA",
    "Sha1": "xxx"
}
}

It's a subtle difference (the sqaure brackets being missing is the issue) but I am not sure to fix it. I am new to dictionaries in Python so please be kind :)

Thanks for any suggestions.

The square brackets mean that it's a list. Do the same in the dictionary:

my_dict = {
    'Bookmarks':[{
        'BookmarkPath': "path/foo/bar",
        'HtmlColor': "#7FCC99",
        'Comment': "AAA",
        'Sha1': "xxx"
    }]
}

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