由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - python remove special chars in JSON string
进入Programming版参与讨论
1 (共1页)
o*****l
发帖数: 539
1
a JSON string like:
{
"a":"{\"type\":\"int\", \"value\":2}"
}
want to convert it to:
{
"a":"{\\"type\\":\\"int\\", \\"value\\":2}"
}
OR
{
"a":"{type:int, value:2}"
}
how to do it, thanks!
m*****e
发帖数: 47
2
>>> js = {
... "a":"{"type":"int", "value":2}"
... }
>>>
>>> js['a']
'{"type":"int", "value":2}'
>>>
>>> str(js['a']).replace('"', '')
'{type:int, value:2}'
>>>
>>> js['a'] = str(js['a']).replace('"', '')
>>>
>>> js
{'a': '{type:int, value:2}'}
>>>
m*****e
发帖数: 47
3
这个invalid:
{
"a":"{\"type\":\"int\", \"value\":2}"
}
See https://jsonchecker.com
m*****e
发帖数: 47
4
到 stack overflow 问会快很多
g*****g
发帖数: 390
5
# original string
s = '"a":"{"type":"int","value":2}'
print(s)
>>> "a":"{"type":"int","value":2}
s # notice the difference between s and print(s)
>>> '"a":"{"type":"int","value":2}'
# first solution looking for, don't like it, but it is what it is
s1 = repr(s).replace("'",'')
print(s1)
>>> "a":"{"type":"int","value":2}
s2 = s.replace('"','') # 2nd solution look for
print(s2)
>>> "a":"{type:int,value:2}
this is in jupyter notebook, >>> means output

【在 o*****l 的大作中提到】
: a JSON string like:
: {
: "a":"{\"type\":\"int\", \"value\":2}"
: }
: want to convert it to:
: {
: "a":"{\\"type\\":\\"int\\", \\"value\\":2}"
: }
: OR
: {

1 (共1页)
进入Programming版参与讨论