3/06/2019

python dic to json, json to txt file (example source code)

This article is about how to convert dic type to json.

source code is like that:
Dic -> Json -> txt file 1
txt file 1 -> Json -> Dic -> Json -> txt file 2

So consequentially, txt file1 and txt file 2 would be same.

Then check source code.

#dictionary type
dic_type = {'dic_type': 'yes', 'json': 10}

#dic to json
import json
str_type = json.dumps(dic_type) #dic to json

#write json to file
f= open("./json.txt","w+")
f.write(str_type)
f.close

#dic from json
dic_type_from_json = json.loads(str_type)

#dic from file
f = open("./json.txt","r")
str_type_from_file = f.read()
f.close
dic_type_from_file = json.loads(str_type_from_file)

#check data type
print( type(str_type) )#Output str
print( type(dic_type_from_json) )#Output dict
print( type(dic_type_from_file) )#Output dict


#write json to file
f= open("./json2.txt","w+")
r = json.dumps(dic_type_from_file)
f.write(r)
f.close

#json.txt and json2.txt is same

No comments:

Post a Comment