

特殊字符的json序列化
source link: https://studygolang.com/articles/14735?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

先来看一段 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)) }
输出结果
{"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 json data = 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还好说,如果跨语言跨部门合作一定需要注意这点(已踩坑)……
Recommend
-
85
序号符号描述1>或1>输出重定向,会清空文件之前的内容2>>或1>>追加输出重定向,在文件尾部追加内容,不会清空文件之前的内容3<或<0输入重定向,会清空文件之前的内容4<<或<<0追加输入重定向,在文件尾部追加内容,不会清空文...
-
88
macOS - @icreeper - 今天我的所有 Apple 设备的 QQ 都无法正常使用了,看到 /t/431004 后,用老版本系统的 iPad 登录 QQ,发现了问题的原因,Google 搜索到了相关新闻 https://www.
-
109
-
71
之前写过一篇关于配置中心对配置内容加密解密的介绍:《Spring Cloud构建微服务架构:分布式配置中心(加密解密)》。在这篇文章中,存在一个问题:当被加密内容包含一些诸如=、+这些特殊字符的时候,使用上篇文章中提到的类似这样的命令curl localhost:7001/encry...
-
10
【前情提要】最近开发过程中遇到一个Tomcat中IllegalArgumentException的报错,所以在这里记录一下。 壹、错误现象在用Get请求是当URL中包含特殊字符,比如:<、>...
-
9
请问批处理编程如何把特殊字符赋值给变量? - V2EX V2EX › Windows 请问批处理编程如何把特殊字符赋值给变量?
-
3
如果数据库用户的密码中带有特殊字符,怎么写 .pgpass 文件。 ...
-
8
重要特殊标记转义字符表_二师兄_Veiking百草园-知识点滴,日常分享 本文搜集整理的是重要特殊标记转义字符,转义字符是很多程序语言、数据格式和通信协议的形式文法的一部分。转义序列通常有两种功能。第一个...
-
5
在 Linux 中使用组合键输出特殊字符
-
6
任何使用过计算机或上过网的人,或多或少遇到过一些键盘上无法直接打出来的...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK