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
Answer from Iman Mirzadeh on Stack Overflowjson.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
json.dumps() returns the JSON string representation of the python dict. See the docs
You can't do r['rating'] because r is a string, not a dict anymore
Perhaps you meant something like
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))
Videos
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_file.read()
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.
Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.
Your JSON dump.txt File:
{"test":"1", "test2":123}
Python Script:
import json
with open('/your/path/to/a/dict/dump.txt') as handle:
dictdump = json.loads(handle.read())
I must first preface this with the fact that Iโm extremely new to python. Like just started learning it a little over a week ago.
I have been racking my brain over how to convert a json object I opened and loaded into a dictionary from a list so I can use the get() function nested within a for loop to do a student ID comparison from another json file (key name in that file is just ID).
Below is the command Iโm trying to load the json file:
With open(โfile.jsonโ) as x: object=json.load(x)
When I print(type(object)), it shows up as class list.
Hereโs a sample of what the json looks like:
[
{
โNameโ: โSteelโ,
โStudentIDโ: 3458274
โTuitionโ: 24.99
},
{
โNameโ: โJoeโ,
โStudentIDโ: 5927592
โTuitionโ: 14.99
}
]
HELP! Thank you!
Isn't JSON format effectively a Python dictionary, in that they follow the same format? Isn't that right? Thanks guys!
Hello all,
I'm going through 100 Days of Python and reading "Introducing Python" by O'Reilly one thing that bothers me is the dict (insert funny joke). But seriously, what's the difference between a dict and a JSON object in JavaScript? Is there really any difference or should I just treat them as the same?
Kind regards
I found two errors in your first example:
- You have a
groupin your stringified (Json) version of your dict. This should be a"group"(with quotes). - You misspelled your variable;
JSON_DatalistโJSON_DataList(lowercase vs. capital L).
After fixing both, I had no problems anymore:
>>> JSON_Datalist = '{"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", "group":{"id": "XXXX"}}}'
>>> the_dict = json.loads(JSON_Datalist)
>>> the_dict
{u'user': {u'username': u'XYZ', u'group': {u'id': u'XXXX'}, u'id': u'XXXX'}, u'id': u'XXXX', u'name': u'xyz'}
after fix the problem group should be "group", below code can meet your requirement
json_data={"id":"XXXX", "name": "xyz", "user" : { "id": "XXXX", "username":"XYZ", "group":{"id": "XXXX"}}}
data = json.dumps(json_data)
json_to_python = json.loads(data)
print (json_to_python)
{'id': 'XXXX', 'name': 'xyz', 'user': {'id': 'XXXX', 'username': 'XYZ', 'group': {'id': 'XXXX'}}}