Reputation: 1221
I have the following string:
{\"Id\":\"135\",\"Type\":0}
The number in the Id field will vary, but will always be an integer with no comma separator. I'm not sure how to get just that value from that string given that it's string data type and not real "XML". I was toying with the replace() function, but the special characters are making it more complex than it seems it needs to be.
is there a way to convert that to XML or something that I can reference the Id value directly?
Upvotes: 0
Views: 31
Reputation: 2180
Non-regex answer as you asked
\"
is an escape sequence in python.
So if {\"Id\":\"135\",\"Type\":0}
is a raw string and if you put it into a python variable like
a = '{\"Id\":\"135\",\"Type\":0}'
gives
>>> a
'{"Id":"135","Type":0}'
OR
If the above string is python string which has \"
which is already escaped, then do a.replace("\\","")
which will give you the string without \
.
Now just load this string into a dict and access element Id
like below.
import json
d = json.loads(a)
d['Id']
Output :
135
Upvotes: 0
Reputation: 27126
Maybe use a regular expression, e.g.
import re
txt = "{\"Id\":\"135\",\"Type\":0}"
x = re.search('"Id":"([0-9]+)"', txt)
if x:
print(x.group(1))
gives
135
It is assumed here that the ids are numeric and consist of at least one digit.
Upvotes: 1