JSON is also used to parse the data from existing files or web browser
The data can only be text - Hence JSON is written in JSON format
- Data types:
A string
A number
and object (JSON Object)
an array
A Boolean
Null
Where is this syntax derived from JavaScript
In JSON data is stored in key value pairs: Name/Value
{"Name": "James", "Age": "18"}
- Data is seperated by a ,
# Here we are importing the Json fileimportjson# Encoding/WRITING from the dictionary and writing Json filecar_data= {"name": "Tesla", "engine": "electric"} # Dictionary# This will print the dictionaryprint(car_data)
# This will print the data type of the dictionaryprint(type(car_data))
car_data_json_string=json.dumps(car_data) # Changing python dictionary to a Json string# The data type is now changed from a dictionary to a stringprint(type(car_data_json_string))
# Lets create a Json file with writing permission "w" stands for writewithopen("new_json_file.json", "w") asjsonfile:
# Enter the name of the file, Permission type# Encoding and creating into a Json filejson.dump(car_data, jsonfile) # Json.dump takes 2 args# Car_data is the first one. It is the dictionary Second is the file object. In this case it is jsonfilewithopen("new_json_file.json") asjsonfile: # Decoding# Reading from the file we just createdcar=json.load(jsonfile) # Storing data from file to car variableprint(type(car)) # Checking the type of data againprint(car["name"]) # To get the values stored in the key called nameprint(car["engine"]) # To get the value of second key pair value# We have DECODED/READING our file new_json.json that we created earlier# We have used dumps(), dump() and load() methods
CRUD stands for "Create, Read, Update and Delete.
These are the four basic database operations.
Many HTTP services model CRUD operations.```
### Exchange rate exercise
```python
# import json
# create a class Exchange_rates
# With required attributes
# fetch the data from exchange_rates.json
# display the data
# display the type of data
# display exchange rates with specific currencies
# Method to return the exchange rates
# Give the full path of the location if not saved within the same folder