Sometimes, we want to get string objects instead of Unicode from JSON with Python.
In this article, we’ll look at how to get string objects instead of Unicode from JSON with Python.
How to get string objects instead of Unicode from JSON with Python?
To get string objects instead of Unicode from JSON with Python, we can use PyYAML to parse the JSON instead of the json
module.
This is because JSON is a subset of YAML.
To install it, we run:
pip install PyYAML
Then we can call the safe_load
method to parse a JSON string into string objects:
import json
import yaml
list_org = ['a', 'b']
list_dump = json.dumps(list_org)
a = yaml.safe_load(list_dump)
print(a)
We convert the list_org
list to JSON with json.dumps
.
Then we call yaml.safe_load
on list_dump
to return list parsed from the list_dump
JSON string.
Therefore, a
is:
['a', 'b']
and both strings are regular strings.
Conclusion
To get string objects instead of Unicode from JSON with Python, we can use PyYAML to parse the JSON instead of the json
module.
This is because JSON is a subset of YAML.