溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

特殊字符的json序列化有哪些

發(fā)布時(shí)間:2021-09-03 15:07:45 來(lái)源:億速云 閱讀:147 作者:小新 欄目:編程語(yǔ)言

這篇文章將為大家詳細(xì)講解有關(guān)特殊字符的json序列化有哪些,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

先來(lái)看一段 golang

package main

import (
 "encoding/json"
 "fmt"
)

func main() {

 data := map[string]string{
 "str0": "Hello, world",
 "str1": "<",
 "str2": ">",
 "str3": "&",
 }
 jsonStr, _ := json.Marshal(data)

 fmt.Println(string(jsonStr))
}

輸出結(jié)果

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

先來(lái)段 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());
}
}

結(jié)果

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

再來(lái)看段 python 的

import json

data = dict(str0='Hello, world',str1='<',str2='>',str3='&')

print(json.dumps(data))

輸出結(jié)果

{"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);
 }
}

輸出結(jié)果

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

總結(jié)

可以看到 python 、 rust 和 java 對(duì)這4個(gè)字符串序列化結(jié)果幾乎是相同的了(除了java序列化后順序有微小變化外),golang明顯對(duì) < ,

> , & 進(jìn)行了轉(zhuǎn)義處理,看看文檔怎么說(shuō)的

// 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.

& 被轉(zhuǎn)義是為了防止一些瀏覽器將JSON輸出曲解為HTML,

而 < , > 被強(qiáng)制轉(zhuǎn)義是因?yàn)間olang認(rèn)為這倆是無(wú)效字節(jié)(這點(diǎn)比較奇怪),

我如果技術(shù)棧都是golang還好說(shuō),如果跨語(yǔ)言跨部門合作一定需要注意這點(diǎn)(已踩坑)……

關(guān)于“特殊字符的json序列化有哪些”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI