Home > Article > Backend Development > How to Retrieve String Objects from JSON in Python 2?
Retrieving String Objects from JSON in Python 2
When parsing JSON in Python 2 from ASCII-encoded text files, string values are automatically cast to Unicode objects. This can pose an issue when interfacing with libraries that exclusively accept string objects.
While updating to Python 3 or using a conversion function are viable solutions, another option is to leverage PyYAML. PyYAML offers a more direct approach by returning string objects as keys and values for JSON files:
<code class="python">import yaml list_org = ['a', 'b'] list_dump = json.dumps(list_org) json_result = json.loads(list_dump) yaml_result = yaml.safe_load(list_dump) print(json_result, type(json_result)) # [u'a', u'b'], <type 'list'> print(yaml_result, type(yaml_result)) # ['a', 'b'], <type 'list'></code>
Note that PyYAML's load function must be replaced with safe_load to ensure compatibility with JSON. Additionally, while ASCII-encoded entries result in string objects, using Unicode-encoded entries will still yield Unicode objects.
If converting string objects to Unicode objects is necessary, the conversion function by Mark Amery can be used:
<code class="python">from mark_amery import unicode_to_str json_list = json.loads(json_list) str_list = unicode_to_str(unicode_list)</code>
The above is the detailed content of How to Retrieve String Objects from JSON in Python 2?. For more information, please follow other related articles on the PHP Chinese website!