How to Convert a List of Dictionaries to Json in Python/Django

Python: converting a list of dictionaries to json

use json library

import json
json.dumps(list)

by the way, you might consider changing variable list to another name, list is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.

How to convert a list of dictionaries to JSON in Python / Django?

return JsonResponse(list_to_json, safe=False)

Take a look at the documentation:

The safe boolean parameter defaults to True. If it’s set to False, any object can be passed for serialization (otherwise only dict instances are allowed). If safe is True and a non-dict object is passed as the first argument, a TypeError will be raised.

Covert a list of dict objects to json but without brakets

You want the json to be a dict with one key -- 'fields', whose value is itself a dict with two keys -- 'cpu0' and 'cpu1'

However, it looks like you created a dictionary with one key: 'fields', and then set its value to json.dumps(my_list).

Instead, you should actually create the object you want, and then convert to json:

flds = dict()       # Create a flds dictionary to collect all the key-value pairs from my_list
for d in my_list: # Iterate over each of the dictionaries in my_list
flds.update(d) # Update flds with all key-value pairs in this dictionary

my_dict = {'fields': flds} # Create the output object
json_str = json.dumps(my_dict) # Dump it to json

print(json_str)

Which outputs:

{"fields": {"cpu0": 0.6, "cpu1": 0.8}}

Converting JSON into Python dict

The string you show is not a JSON-coded object (eqv to a Python dict) — more like an array (eqv to a list) without brackets and with a stray extra comma at the end. So (using simplejson for version portability — the standard library's json in 2.6 is fine too of course!-):

>>> import simplejson
>>> js = "{\"description\":\"fdsafsa\",\"order\":\"1\",\"place\":\"22 Plainsman Rd, Mississauga, ON, Canada\",\"lat\":43.5969175,\"lng\":-79.7248744,\"locationDate\":\"03/24/2010\"},{\"description\":\"sadfdsa\",\"order\":\"2\",\"place\":\"50 Dawnridge Trail, Brampton, ON, Canada\",\"lat\":43.7304774,\"lng\":-79.8055435,\"locationDate\":\"03/26/2010\"},"
>>> simplejson.loads('[%s]' % js[:-1])
[{'description': 'fdsafsa', 'order': '1', 'place': '22 Plainsman Rd, Mississauga, ON, Canada', 'lat': 43.596917500000004, 'lng': -79.724874400000004, 'locationDate': '03/24/2010'}, {'description': 'sadfdsa', 'order': '2', 'place': '50 Dawnridge Trail, Brampton, ON, Canada', 'lat': 43.730477399999998, 'lng': -79.805543499999999, 'locationDate': '03/26/2010'}]

If you really want a dict you'll have to specify how to treat these two unnamed items, i.e., what arbitrary keys you want to slap on them...?



Related Topics



Leave a reply



Submit