python中json串特殊字符替换问题

在json串中发现特殊字符”\n”,使用str.replace("\n","")进行替换,在终端测试ok。但是脚本运行(从文件中读取json串)一直不能成功,后使用str.replace("\\n","")替换成功!

参考链接:https://www.jianshu.com/p/c0cce1b5469a

字符串转json 和字典的异同

相同点

都是键值对
转换字符串到对象时,字符串中转义字符(比如 “\r\n” or “”abc”“)需要像这样表示:"\\r\\n" or "\\"abc\\""
字符串除了键值对不能有其它字符,比如代码注释! ‘#’

不同点

json key不能使用单引号,字典可以
json使用json.load(str)解析字符串
字典使用evalI()函数解析字符串

json

import json
user = '''
{
"name":"jim\\r\\n",
"sex":"\\"male\\"",
"age":"18"
}
'''
print user

jsonuser = json.loads(user)
print jsonuser["name"].encode()
print jsonuser["sex"].encode()

结果输出:

{
"name":"jim\r\n",
"sex":"\"male\"",
"age":"18"
}

jim

"male"

字典

import json
user = '''
{
'name':'jim\\r\\n',
'sex':'"male"',
'age':'18'
}
'''
print user

dicuser = eval(user)
print dicuser["name"]
print dicuser["sex"]

运行结果

{
'name':'jim\r\n',
'sex':'"male"',
'age':'18'
}

jim

"male"

猜你喜欢

转载自blog.csdn.net/marywang56/article/details/80568822