先來看一段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"}
可以看到python
、rust
和java
對這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還好說,如果跨語言跨部門合作一定需要注意這點(已踩坑)……