scientific_comp_projects/CODE/[python]XML_JSON/json_parse_intro.py
2021-10-29 15:16:40 +02:00

54 lines
1.5 KiB
Python

'''
Parsing functions :
obj = load(file) # file
obj = loads(string) # string suppost
Serialization functions :
dump(obj, file)
str = dumps(obj)
Conversion convention
--Serialization--> --Parsing-->
Python object | JSON Repr | Python object
------------------------------------------------------------
dict | object | dict
list, tuple | array | list
str | string | str
int, long, float, Enums | number | int, float- depends
True | true | True
False | false | False
None | null | None
'''
# Process JSON data returned from a server
# TODO : use the JSON module
import json
def main() :
# define a string of JSON code
jsonStr = '''{
"sandwich" : "Reuben",
"toasted" : true,
"toppings" : [
"Thousand Island Dressing",
"Sauerkraut",
"Pickles"
],
"price" : 8.99
}'''
# TODO : parse the jason data using loads
data = json.loads(jsonStr)
# TODO : print information from the data structure
print('Sandwich :' + data['sandwich'])
if (data['toasted']):
print('and it is toasted !')
for topping in data['toppings']:
print('Topping : ' + topping)
if __name__ == '__main__':
main()