JSON supplemental content [solve Chinese garbled, connected]
Import json# english Display dic = {"Hello": "World"}STR = Json.dumps (DIC) # type (str) <class ' str ' > str: {"Hello": "World"}print ("Type (str)", type (str), ' str: ', str) # Chinese Display r = {"Key": "China"}st = Json.dumps (r) # becomes a string after serialization, Chinese becomes ASCII encoded # type (ST) <clas S ' str ' > ST: {"key": "\U4E2D\U56FD"}print ("Type (ST)", type (ST), ' St: ', st) # chinese bytes Processing b = Bytes (St, encoding= "Utf-8") # t Ype (b): <class ' bytes ' > b:b ' {"key": "\\u4e2d\\u56fd"} ' # send utf-8 bytes to server print ("type (b):", type (b), "B:", b) # Solution one: No Use Ensure_ascill encoding k = {"key": "China"}new = Json.dumps (k, ensure_ascii=false) print (new) # {"Key": "China"}BB = bytes (new, Encod ing= "Utf-8") print (BB) # b ' {"Key": "\xe4\xb8\xad\xe5\x9b\xbd"} ' # solution two: First the MSG information in the dictionary is handled in placeholder, then the json.dumps[is a string now], Then use the placeholder to pass in MSG information L = {"key": '% (msg) s '} # Note Quotes New1 = json.dumps (l) print (New1) # {"Key": "% (msg) S"}new1 = New1%{' msg ': ' China '}print (new1) # {"Key": "China"}pp = bytes (new, encoding= "Utf-8") print (PP) # b ' {"Key": "\XE4\XB8\XAD\XE5\X9B\XBD"} "", General: Problem location: Json.dumps () will be in ChineseThe ASCII encoding [default encoding] After returning the encoded string "\U4E2D\U56FD" bytes () converts a string into bytes to send "\\U4E2D\\U56FD" after the message is received, byte-to-string STR is converted, and then sent to the former Console namely "\\U4E2D\\U56FD"-"\U4E2D\U56FD"-"garbled problem solved: 1." If ASCII encoding is not used, the byte encoding Json.dumps (K, Ensure_ascii=false) 2 is returned directly to Chinese. Use placeholders to pass in MSG information after Json.dumps () go in J = J%{"MSG": Msg}--Now display Chinese ""
Json.dumps (CLS parameter contents and conversion rules)
If CLS is None: cls = jsonencoder+-------------------+---------------+| Python | JSON |+===================+===============+| dict | object |+-------------------+---------------+| List, tuple | array |+-------------------+---------------+| str | string |+-------------------+--- ------------+| int, Float | number |+-------------------+---------------+| True | true |+-------------------+---------------+| False | false |+-------------------+---------------+| None | null |+-------------------+---------------+
Python Learning---json supplemental content [Chinese encoding + dumps parsing]