I 've been tossing for several hours. Come on, remember it!
JSON: Xs Chinese compatibility problems recently encountered a encoding problem. The first line in the figure is the correct content, and the second and third lines are JSON fragments: because the data source has various directions, some are transcoded and some are not. When JSON: Xs is used to generate JSON, the Generated Chinese content is sometimes garbled. Later I found out the problem: JSON: XS, when encoding UTF-8, the input variable must be a scalar represented as UTF-8 in Perl, rather than raw data. It may be related to the implementation of JSON: Xs in C language. After the processing, it is finally normal: the code to reproduce the problem and solve the problem is as follows: file encoding: UTF-8
#! /Usr/bin/perluse JSON: Xs; Use encode; Use Data: dumper; use strict; Use warnings; my $ content = "this is a piece of Chinese content "; print "internal representation before transcoding: \ n"; print dumper $ content, "\ n"; print "JSON: \ n" before transcoding; print JSON :: XS-> New-> utf8-> encode ({content => $ content}), "\ n ";
# After you transcode the content once, you can normally output JSON. $ content = decode ("UTF-8", $ content); print "transcoded internal representation: \ n "; print dumper $ content, "\ n"; print "transcoded JSON: \ n"; print JSON :: XS-> New-> utf8-> encode ({content => $ content}), "\ n"; the output result is as follows: internal representation before transcoding: $ var1 = 'this is a piece of Chinese content'; $ var2 = ''; JSON before transcoding: {" content ":: $ var1 = "\ x {8fd9} \ x {662f} \ x {4e00} \ x {6bb5} \ x {4e2d} \ x {6587} \ x {5185 }\ X {5bb9 }"; $ var2 = ''; transcoded JSON: {" content ":" This is a piece of Chinese content "}