There's just a slight problem with your for loop.
james@VIII:~/Desktop$ ls
f.txt
james@VIII:~/Desktop$ cat f.txt
{
"Ask":
{"0":[[9.13,30200],[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589]],
"1":[[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589],[9.18,37521]] },
"Bid":
{"0":[[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381],[9.08,98178]],
"1":[[9.13,13500],[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381]]}
}
james@VIII:~/Desktop$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('f.txt') as f_in:
... data = json.load(f_in)
...
>>> data
{'Ask': {'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}, 'Bid': {'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}}
>>> data['Ask']
{'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}
>>>
>>> data['Bid']
{'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}
>>> for x in data['Bid']['0']:
... print(x)
...
[9.12, 198807]
[9.11, 1110]
[9.1, 42110]
[9.09, 84381]
[9.08, 98178]
Your for loop just needed to be changed a little.
PS you don't need to specify 'r' when reading the file.
You can also get individual values like this:
>>> for x in data['Bid']['0']:
... print(str(x[0]) + ': ' + str(x[1]))
...
9.12: 198807
9.11: 1110
9.1: 42110
9.09: 84381
9.08: 98178
Answer from m.a.d.cat on Stack OverflowReading ALL objects into a list from a JSON file in Python - Stack Overflow
How do I read a list of JSON files from file in python? - Stack Overflow
Convert JSON array to Python list - Stack Overflow
python - function to read json data from file and convert t into a list - Stack Overflow
There's just a slight problem with your for loop.
james@VIII:~/Desktop$ ls
f.txt
james@VIII:~/Desktop$ cat f.txt
{
"Ask":
{"0":[[9.13,30200],[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589]],
"1":[[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589],[9.18,37521]] },
"Bid":
{"0":[[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381],[9.08,98178]],
"1":[[9.13,13500],[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381]]}
}
james@VIII:~/Desktop$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('f.txt') as f_in:
... data = json.load(f_in)
...
>>> data
{'Ask': {'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}, 'Bid': {'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}}
>>> data['Ask']
{'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}
>>>
>>> data['Bid']
{'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}
>>> for x in data['Bid']['0']:
... print(x)
...
[9.12, 198807]
[9.11, 1110]
[9.1, 42110]
[9.09, 84381]
[9.08, 98178]
Your for loop just needed to be changed a little.
PS you don't need to specify 'r' when reading the file.
You can also get individual values like this:
>>> for x in data['Bid']['0']:
... print(str(x[0]) + ': ' + str(x[1]))
...
9.12: 198807
9.11: 1110
9.1: 42110
9.09: 84381
9.08: 98178
your for is loop in the keys of dict.
for x in data["Bid"]:
print(type(x))
# <class 'str'>
try it:
for x in data['Bid']['0']:
print(x)
or
for x in data['Bid'].values():
print(x)
sorry for my English :)
I think you have a couple issues going on here. First, valid JSON doesn't use single quotes ('), it is all double quotes ("). You are looking for something like:
[{
"id":123,
"emotions":[],
"lyrics":"AbC",
"emotionID":0,
"artist":"222",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
},
{
"id":123,
"emotions":[],
"lyrics":"EFG",
"emotionID":0,
"artist":"223",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
}
]
Secondly, you need to open the json file for reading and then load it as json. The following should work for you:
with open(read_file) as file:
data = json.load(file)
with open(write_file, 'w') as file:
json.dump(data, file)
print(data)
data.append(json.loads(f))
This appends the list you read from the JSON file as a single element to the list. So after your other append, the list will have two elements: One list of songs, and that one song object you added afterwards.
You should use list.extend to extend the list with the items from another list:
data.extends(json.loads(f))
Since your list is empty before that, you can also just load the list from the JSON and then append to that one:
data = json.loads(f)
data.append(vars(songObj))
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
To import a json file, I recommend using the json libary. In your example, you would first need to import it.
import json
Then you can use
with open('filename.json', 'r') as fp:
data = json.load(fp)
to get the data. Note that load is different from 'loads' (https://docs.python.org/2/library/json.html). You just need to change 'content' to 'fp' since that is how you referred to your file.
Note that this code stores returns the json as a dict, not as a list, which is different than what you are asking about, but probably what you want to use not knowing more about what you are trying to do.
You can basically use the builtin json module. Full documentation here : https://docs.python.org/3/library/json.html
To get a json string from object (any data like list, dict, etc...), use :
import json
json_str = json.dumps(my_data) # Get json string representation of my_data
fp.write(json_str) # Write json_str string to file fp
Once you wrote your file you can read the json string from file with :
json_str = fp.read()
And finally turn to a python object :
import json
my_data = json.loads(json_str)
It's not loading your content basically because it's not a valid json format, try this script:
import json
try:
file_content = """{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}"""
json.loads(file)
except Exception as e:
print("This is not JSON!")
print('-' * 80)
file_content = """[{"uid": 2, "user": 1},
{"uid": 2, "user": 1},
{"uid": 2, "user": 1}]"""
print(json.loads(file_content))
The result will be:
This is not JSON!
--------------------------------------------------------------------------------
[{'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}, {'user': 1, 'uid': 2}]
Proving that if if you wrap your dictionary into brackets and separate the items with commas the json will be parsed correctly
Of course, If you don't want to tweak your file at all, you can do something like this to create your output:
import json
file_content = """{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
{"uid": 2, "user": 1}
"""
output = [json.loads(line)
for line in file_content.split("\n") if line.strip() != ""]
print(output)
Your file is not a JSON, its a list of JSON.
with open(filec , 'r') as f:
list = list(map(json.loads, f))
You can "convert" a string that contains a list to an actual list like this
>>> import ast
>>> ast.literal_eval('[{"a":1, "c":4},{"b":2, "d":5}]')
[{'a': 1, 'c': 4}, {'b': 2, 'd': 5}]
You can of course sub out the literal string for the data you read from file
Another, more dirty option is this (it will produce list of strings):
a = str('[{"a":1, "c":4},{"b":2, "d":5}]')
b = list()
for i in a.replace('[','').replace(']','').split(sep='},'):
b.append(i+'}')
b[len(b)-1] = b[len(b)-1].replace('}}','}')
for i in b:
i
'{"a":1, "c":4}'
'{"b":2, "d":5}'
Since ast proposed by Tim earlier will go deaper than first level, it will actually convert underlying string into dictionary. So instead of list of strings you will get list of dictionaries. I am not sure if that's what you want to get.
json_data = [] # your list with json objects (dicts)
with open('prueba.json') as json_file:
json_data = json.load(json_file)
for item in json_data:
for data_item in item['data']:
print data_item['name'], data_item['value']
Something like
for key, value in json_data.iteritems():
print key
if isinstance(value, (list, tuple)):
for item in value:
print item
if isinstance(value, (dict)):
for value_key,value_value in value.iteritems():
print value_key,str(value_value)
Can be improved to manage more types and can be made recursive.