How To Escape Characters When Reading JSON
Question
I need to write out all the variables in this JSON response:
"result": {
"\/common\/topic\/weblink": [
{
"url": "http:\/\/www.boardgamegeek.com\/boardgame\/13",
"description": "BoardGameGeek"
}
],
"id": "\/en\/settlers_of_catan"
}
So to get the id:
result.id
But how do I get the values for "\/common\/topic\/weblink"?
Solution
You want something like
result["\/common\/topic\/weblink"][0].url
(I think)
OTHER TIPS
"\/common\/topic\/weblink"
resolves to the string /common/topic/weblink
. Any API accessing the decoded content should use the resulting unescaped data; the escaping is just part of JSON's encoding.
This works fine, using the standard JSON module included in Python, which I strongly recommend you use rather than third-party ones unless you have a very strong reason to be different:
import json
json_data = r"""
{
"result": {
"\/common\/topic\/weblink": [
{
"url": "http:\/\/www.boardgamegeek.com\/boardgame\/13",
"description": "BoardGameGeek"
}
],
"id": "\/en\/settlers_of_catan"
}
}"""
data = json.loads(json_data)
print data["result"]["/common/topic/weblink"]
Note that you left out the enclosing braces on the object, which I added in.
Try
result.__getattribute__("\/common\/topic\/weblink")[0].url
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow