JSON: Chinese compatibility of XS

Source: Internet
Author: User
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 "}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.