JSON
JSON - dict format
pickle - binary format
variable=json.loads(dict enclosed in " " ) variable-type=dict
variable2=json.dumps(dict) variable type=str
use double inverted commas only
json.dump(dict,file loc)
variable3=json.load(file loc)
same for pickling just replace json with pickle
pretty print works with dump and dumps
print(json.dumps(json_dict,indent=5,sort_keys=True))
example codes:
CODE1
import json
import requests
def main():
data={
'username':"james",
'active':True,
'subscribers':10,
'orders_total':10.39,
'orders_ids':['abc','83m','hhd9']
}
# print(data)
s=json.dumps(data)
print(s)
print(type(s))
data2=json.loads(s)
# assert data2==data
print(data2)
# with open('file.json','w') as f:
# json.dump(data,f)
# with open(file.json','r') as f:
# data3=json.load(f)
# assert data3==data
# print(data3)
# r=requests.get('https://jsonplaceholder.typicode.com/users')
# print(r.json())
if __name__=="__main__":
main()
CODE2
import json
json_string='{"hello":103,"hello2":"krish"}'
json_dict=json.loads(json_string)
print(json_dict)
print(json_dict["hello"])
# JSON-dict,list,tuple,str,int,boolen,none,float can be interconverted
# pretty print --dump/dumps
print(json.dumps(json_dict,indent=5,sort_keys=True))
Comments
Post a Comment
For any queries or suggestions
Comment Here