当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > 特殊字符的json序列化总结大全

特殊字符的json序列化总结大全

2018年09月23日  | 移动技术网IT编程  | 我要评论

前言

json 数据中的string 传递数据时,需要处理好特殊字符.本文主要给大家总结介绍了关于golang、rust、java和python对特殊字符的json序列化处理操作,下面话不多说了,来一起看看详细的介绍吧

先来看一段 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还好说,如果跨语言跨部门合作一定需要注意这点(已踩坑)……

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网