Convert a list to json in Python
You can convert a list to a JSON string.
import json
s = [1, 2, 3, 'a']
j = json.dumps(s)
print(j) # [1, 2, 3, "a"]
print(type(j)) # <class 'str'>
s
is a list and j
is a string formatted in JSON, which can be created by json.dumps()
. Writing a list in a json file needs that conversion.
import json
s = [1, 2, 3, 'a']
j = json.dumps(s)
with open('a.json', 'w') as f:
f.write(j)
a.json
[1, 2, 3, "a"]
Python List
- Get the number of elements
- Append an element
- Extend a list
- Reverse a list
- Sort a list
- Shuffle a list
- Get the index of an element
- Pop an element
- Delete an element from a list
- Clear a list
- Empty list
- Python range
- Get the range of integers
- Get a random element from a list
- Join a list
- Get keys and values iterating a list
- List comprehension
- Get the last element
- Insert an object at the first position
- Get the index of the max value
- Convert a list to a tuple
- Convert a list to json
- Filter
- Iterate lists in parallel
- Generator
- Make a cartesian product
- Sort a list of tuples by the first or second element