Converting Dictionary to JSON

Converting dictionary to JSON

json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method

See json.dumps() as a save method and json.loads() as a retrieve method.

This is the code sample which might help you understand it more:

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

How do I convert a dictionary to a JSON String in C#?

Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.

For a Dictionary<int, List<int>> as you have specified, you can use Linq:

string MyDictionaryToJson(Dictionary<int, List<int>> dict)
var entries = dict.Select(d =>
string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";

But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.

Cannot convert Dictionary to JSON object using json.dumps() in python

I could not recreate the error, but json.dumps worked fine for me. Please refer to the screenshot below:

Code sample and output

Code I tried:

import json
JsonData={'list': {'Elements': [{'text': 'Task 1', 'Shape': 'Decision', 'id': 0},
{'text': 'Task 2', 'Shape': 'Decision', 'id': 1},
{'text': 'Task 3', 'Shape': 'Decision', 'id': 2},
{'text': 'Task 4', 'Shape': 'Decision', 'id': 3},
{'text': 'Task 5', 'Shape': 'Rectangle', 'id': 4},
{'text': 'Task 6', 'Shape': 'Decision', 'id': 5}],
'links': [{'source': 0, 'target': 1, 'key': 0},
{'source': 0, 'target': 4, 'key': 0},
{'source': 1, 'target': 2, 'key': 0},
{'source': 1, 'target': 3, 'key': 0},
{'source': 2, 'target': 1, 'key': 0},
{'source': 2, 'target': 4, 'key': 0},
{'source': 3, 'target': 1, 'key': 0},
{'source': 3, 'target': 4, 'key': 0},
{'source': 4, 'target': 5, 'key': 0},
{'source': 5, 'target': 4, 'key': 0},
{'source': 5, 'target': 1, 'key': 0}]}}

conversion of python dictionary to json types in django rest framework

This is being handled by Response class.
Response class takes unrendered, serialized data of the response and status code as argument. If you look at the implementation it chooses the render classes based on the accepted_media_type. By default django support following renderers by default.


In your case django uses JSONRenderer class which has a render method which does the actual serialization into JSON

How to convert python dict to json

I am not completely understand What is JSON and its format that is my problem.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

I refer this

The valid JSON string is '{"key1":"value1","key2":"value2"}'

Thank you

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str =
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Related Topics

Leave a reply