data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
How to parse JSON file into Python list - Stack Overflow
How to create a json file from list 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
Videos
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 :)
Convert the lists to list of dictionaries and dump this to the file
arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100, 3400, 200]
with open('file.json', 'w') as file:
json.dump([{'user': id, 'wallet amount': amount} for id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)], file)
file.json
[{"user": 1, "wallet amount": 100}, {"user": 2, "wallet amount": 3400}, {"user": 3, "wallet amount": 200}]
Another simple solution, using enumerate:
import json
arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100,3400,200]
jsonfile=[]
for index, value in enumerate(arr_of_id_by_user):
jsonfile.append({
"user": value,
"waller_amount": arr_of_wallet_amount[index]
})
print (json.dumps(jsonfile, indent=4))
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
I have a sqlite database were I store my workout exercises. I have been working to get these exercises into a JSON files to send to my website to display graphs using Chartjs.
Going through this article (https://changsin.medium.com/how-to-serialize-a-class-object-to-json-in-python-849697a0cd3) they take two objects and turn them into a JSON output. Like this:
label1 = Label("person", 10, 10, 4, 10)
label2 = Label("car", 20, 20, 5, 11)
image_bboxes = {"image1.jpg": [label1, label2]}
output:
{"version": 1,
"type": "box",
"bounding box":
{"image1":
[{"label": "person",
"x": 10,
"y": 20
},
{"label": "car",
"x": 10,
"y": 20
}
]
}
}Now I have a list of lists looking like this:
all_exercises = [[planks1, planks2],[bench1,bench2]]
I want to create a JSON output that will allow me to pass it off to my website. Then use JS and Chartjs to display the user selected graph. I can get the graph to do what I want it to do. I don't know how to make the JSON output. I'm not understanding something fundamental when I am using JSON. I just don't know what it is. A book or resource would be greatly appreciated.
My output currently looks like this:
{
"version": 1,
"exertest": {
"second": [
{ //Need's to be labeled PLANK here
"id": 325,
"interval": 1,
"resistance": 0,
"set_number": 1,
"workout_id": 58,
"workout_date": "2022-03-28T06:00",
"exercise_id": 24,
"exercise_name": "Plank"
},
{
"id": 326,
"interval": 1,
"resistance": 0,
"set_number": 2,
"workout_id": 58,
"workout_date": "2022-03-28T06:00",
"exercise_id": 24,
"exercise_name": "Plank"
},
{ // Needs to be labeled HIP BRIDGE here
"id": 327,
"interval": 15,
"resistance": 0,
"set_number": 1,
"workout_id": 58,
"workout_date": "2022-03-28T06:00",
"exercise_id": 25,
"exercise_name": "Hip Bridge"
}
]
}
}
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!
I am learning Python, and in particular, working with JSON and sqlite in Python. Ultimately I plan to use Python to load the JSON into a sqlite database.
Here is the question: Is there a way in to list all of the keys from a JSON file (not from a string) using Python? I want a list of all of the keys so I can determine what columns I will need/use in my sqlite table(s), without having to manually read the file and make a list.
BTW, this is something along the lines of using INFORMATION_SCHEMA.COLUMNS in SQL Server, or the FINDALL in Python for XML.
All of this is for personal learning, so I'm not looking to use other technologies, I'm sticking to Python, JSON, and sqlite on purpose.
I know that, list can be converted into JSON by using json.dumps(mylist).
But how can I convert something like this into JSON ?
[["abc", "bcd", "cde"] , ["pgr", "xyz"]]