JSON is a lightweight data interchange format that is commonly used in HTTP requests and is often seen in daily operations.
Conversion of 1.json types and Python data
function conversion corresponding relational table:
Python |
Json |
Dict |
Object |
List, tuple |
Array |
STR, Unicode |
String |
int, long, float |
Number |
True |
True |
False |
False |
None |
Null |
1) The JSON data Write file :json.dump ()
Example:
Import JSON
Json_data = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6}
f = open ("A.txt", "W")
Json.dump (json_data,f)
F.close ()
Result: A.txt file generated under directory, content:
{"A": 1, "C": 3, "B": 2, "E": 5, "D": 4, "F": 6}
2) Read the json data in the file and display it in Unicode type format: json.load ()
Import JSON
# Json_data = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6}
# f = open ("A.txt", "W")
# Json.dump (json_data,f)
# F.close ()
F2 = open ("A.txt", "R")
Dict2 = Json.load (F2)
Print (DICT2)
Results:
{u ' a ': 1, U ' C ': 3, U ' B ': 2, U ' E ': 5, U ' d ': 4, U ' F ': 6}
3) Python Dictionary--(conversion) JSON string :json.dumps ()
Example:
Import JSON
m = {"Success": "Yes", "message": "Hello"}
Json_str = json.dumps(m)
Print (m)
Print (Type (m))
Print (JSON_STR)
Print (Type (JSON_STR))
Results:
{' message ': ' Hello ', ' success ': ' Yes '}
<type ' Dict ' >
{"Message": "Hello", "Success": "Yes"}
<type ' str ' >
4) Pyhton dictionary with JSON string (decode): json.loads ()
Example:
Import JSON
m = {"Success": "Yes", "message": "Hello"}
Json_str = Json.dumps (M)
Print (JSON_STR)
Print (Type (JSON_STR))
Json_dict = Json.loads (JSON_STR)
Print (json_dict)
Print (Type (json_dict))
Results:
{"Message": "Hello", "Success": "Yes"}
<type ' str ' >
{u ' message ': U ' hello ', U ' success ': U ' Yes '}
<type ' Dict ' >
2. Crawler examples
Import JSON
Import Urllib2
from pip._vendor.requests.packages Import Chardet
URL = '/http '
req = Urllib2. Request (URL)
res = Urllib2.urlopen (req)
result = Res.read ()
Print (Chardet.detect (result))
m = json.loads (Result)
Print (type(m))
Print (m)
Use of Python JSON files