json_Python、関数dumps、loads、dump、load

15662 ワード

      https://blog.csdn.net/bozhanggu2239/article/details/80832644
"""dumps、loads 、  、dump、load"""



#  json.dumps()   dict       str,       dict       json        ,                
"""
import json

first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
dumps = json.dumps(first)

print(first) #{'a': '1111', 'c': '3333', 'b': '2222', 'd': '4444'}
print(dumps)    #{"a": "1111", "c": "3333", "b": "2222", "d": "4444"}
print(type(first))   #
print(type(dumps))      #
print(type("fw"))   #
print(type('sf'))   #

Y='_3dumpload.json'                #          .json           JSON  
# with open(Y,'w') as f_obj:
#     f_obj.write(first)    #TypeError: write() argument must be str, not dict
#     
with open(Y,'w') as f_obj:
    f_obj.write(dumps)          #{"d": "4444", "a": "1111", "b": "2222", "c": "3333"}
#{"d": "4444", "a": "1111", "b": "2222", "c": "3333"}  dump,  :
#"{\"a\": \"1111\", \"b\": \"2222\", \"c\": \"3333\", \"d\": \"4444\"}"\

"""

#json.loads()   str       dict。
"""
import json

first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
dumps = json.dumps(first)
dumps_loads = json.loads(dumps)

print(first)            #{'b': '2222', 'd': '4444', 'a': '1111', 'c': '3333'}
print(dumps)            #{"d": "4444", "a": "1111", "c": "3333", "b": "2222"}
print(dumps_loads)      #{'b': '2222', 'd': '4444', 'a': '1111', 'c': '3333'}

print(type(first))          #
print(type(dumps))          #
print(type(dumps_loads))    #
"""

#  
"""
import json
first = {'a': '1111', 'b': '2222', 'c': '3333', 'd': '4444'}
dumps = json.dumps(first) #{"d": "4444", "b": "2222", "a": "1111", "c": "3333"}#
dumps2 =json.dumps(dumps) #"{\"d\": \"4444\", \"b\": \"2222\", \"a\": \"1111\", \"c\": \"3333\"}"
dumps3 =json.dumps(dumps2) #"\"{\\\"d\\\": \\\"4444\\\", \\\"b\\\": \\\"2222\\\", \\\"a\\\": \\\"1111\\\", \\\"c\\\": \\\"3333\\\"}\""
dumps4 =json.dumps(dumps3) #"\"\\\"{\\\\\\\"d\\\\\\\": \\\\\\\"4444\\\\\\\", \\\\\\\"b\\\\\\\": \\\\\\\"2222\\\\\\\", \\\\\\\"a\\\\\\\": \\\\\\\"1111\\\\\\\", \\\\\\\"c\\\\\\\": \\\\\\\"3333\\\\\\\"}\\\"\""
print(dumps)
print(dumps2)
print(dumps3) #      dumps  dump     
print(dumps4)#        
"""

#dump load    dumps loads   ,             ,      
#  json.dump(numbers,f_obj),             
# dumpshe     。dumps = json.dumps(first)
# with open(Y,'w') as f_obj:
#     f_obj.write(dumps)        2  ,      
"""
import json                     #    json
numbers ={'2':3,'5':7,'11':13}
Y='_3dumpload.json'                #          .json           JSON  
with open(Y,'w') as f_obj:
    json.dump(numbers,f_obj)    #        {"2": 3, "11": 13, "5": 7}

A='_3dumpload.json'
with open(A) as f:
    num=json.load(f)            #  json.load(f)     numbers.json'    
print(num)                      #{'11': 13, '5': 7, '2': 3}

"""