The JSON object you have is a list of dictionaries (one at least), so you simply need to grab the first element of the list.
d = a[0]
d['text']
Answer from Kyle James Walker on Stack Overflow
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!
Python: converting a list of dictionaries to json - Stack Overflow
How to convert Python dict to JSON as a list, if possible - Stack Overflow
Python: JSON string to list of dictionaries - Getting error when iterating - Stack Overflow
convert list of dictionary to list of json objects
Videos
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.
import json
list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
Write to json File:
with open('/home/ubuntu/test.json', 'w') as fout:
json.dump(list , fout)
Read Json file:
with open(r"/home/ubuntu/test.json", "r") as read_file:
data = json.load(read_file)
print(data)
#list = [{'id': 123, 'data': 'qwerty', 'indices': [1,10]}, {'id': 345, 'data': 'mnbvc', 'indices': [2,11]}]
I don't know of a solution without recursion... Although you can call your converter from inside the encode method of your custom Encoder, it would just add unnecessary complexity.
In [1]: import json
In [2]: d = {"0": "data0", "1": "data1", "2": {"0": "data0", "1": "data1", "2": "data2"}}
In [3]: def convert(obj):
...: if isinstance(obj, (list, tuple)):
...: return [convert(i) for i in obj]
...: elif isinstance(obj, dict):
...: _, values = zip(*sorted(obj.items()))
...: return convert(values)
...: return obj
In [4]: json.dumps(convert(d))
Out[4]: '["data0", "data1", ["data0", "data1", "data2"]]'
You could convert the dictionary into a list of tuples and then sort it, as dictionary items won't necessarily come out in the order than you want them to:
items = sorted(d.items(), key=lambda item: item[0])
values = [item[1] for item in items]
json_dict = json.dumps(values)
Your JSON data is a list of dictionaries, so after json.loads(s) you will have jdata as a list, not a dictionary.
Try something like the following:
Copyimport json
s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
jdata = json.loads(s)
for d in jdata:
for key, value in d.iteritems():
print key, value
json.loads(s) will return you list. To iterate over it you don't need iteritems.
Copy>>> jdata = json.loads(s)
>>> for doc in jdata:
... for key, value in doc.iteritems():
... print key, value
How to convert list of dictionary to list of json objects?
input = [{'a':'b'},{'c':'d'}]
expectedOutput = [{"a":"b"},{"c":"d"}]
I tried following but couldn't get expected result
-
json.dumps(input)gives string'[{"a":"b"},{"c":"d"}]' -
Iterate through dictionary and convert each dict to json object gives
['{"a":"b"}','{"c":"d"}']
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 have a JSON array file that I want to convert to a dictionary. The file has only one pair of square brackets [] with a dictionary of sub dictionaries inside it. print(len(dict)) returns 14. I want to simply convert the file to a dict but using json.loads() creates a list and using json.loads(filename)[0] to get that sole large item of nested dictionaries inside the json array only returns the first dictionary object and not the entire 14.
I want to know if there’s another way of doing this besides a dictionary comprehension which I found, but don’t necessarily understand. Thanks.