json.dumps()
is used to decode JSON dataimport json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
output:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
json.loads()
is used to convert JSON data into Python data.import json
# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'
# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)
print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])
print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])
output:
arrayJson to list_data :
[1, 1.5, ['normal string', 1, 1.5]]
Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]
objectJson to dictionary :
{'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}
Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
| JSON | Python |
|:-------------:|:------:|
| object | dict |
| array | list |
| string | str |
| number (int) | int |
| number (real) | float |
| true | True |
| false | False |