特殊字元的json序列化

來源:互聯網
上載者:User

先來看一段golang

package mainimport (    "encoding/json"    "fmt")func main() {    data := map[string]string{        "str0": "Hello, world",        "str1": "<",        "str2": ">",        "str3": "&",    }    jsonStr, _ := json.Marshal(data)    fmt.Println(string(jsonStr))}

輸出結果

{"str0":"Hello, world","str1":"\u003c","str2":"\u003e","str3":"\u0026"}

先來段rust

extern crate rustc_serialize;use rustc_serialize::json;use std::collections::HashMap;fn main(){    let mut data =  HashMap::new();    data.insert("str0","Hello, world");    data.insert("str1","<");    data.insert("str2",">");    data.insert("str3","&");    println!("{}", json::encode(&data).unwrap());}}

結果

{"str0":"Hello, world","str2":">","str1":"<","str3":"&"}

再來看段python

import jsondata = dict(str0='Hello, world',str1='<',str2='>',str3='&')print(json.dumps(data))

輸出結果

{"str0": "Hello, world", "str1": "<", "str2": ">", "str3": "&"}

再看看java的

import org.json.simple.JSONObject;class JsonDemo{    public static void main(String[] args)    {        JSONObject obj = new JSONObject();        obj.put("str0", "Hello, world");        obj.put("str1", "<");        obj.put("str2", ">");        obj.put("str3", "&");        System.out.println(obj);    }}

輸出結果

{"str3":"&","str1":"<","str2":">","str0":"Hello, world"}

可以看到pythonrustjava對這4個字串序列化結果幾乎是相同的了(除了java序列化後順序有微小變化外),golang明顯對 < ,
> , & 進行了轉義處理,看看文檔怎麼說的

// String values encode as JSON strings coerced to valid UTF-8,
// replacing invalid bytes with the Unicode replacement rune.
// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e"
// to keep some browsers from misinterpreting JSON output as HTML.
// Ampersand "&" is also escaped to "\u0026" for the same reason.

& 被轉義是為了防止一些瀏覽器將JSON輸出曲解為HTML,
< ,> 被強制轉義是因為golang認為這倆是無效位元組(這點比較奇怪),
我如果技術棧都是golang還好說,如果跨語言跨部門合作一定需要注意這點(已踩坑)……

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.