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

Time:11-17

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.

CodePudding user response:

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"
    }]
}
  • Related