Home > Article > Backend Development > How to Convert JSON Data to String Objects in Python 2?
How to Get String Objects from JSON in Python 2
Accessing JSON data using Python can yield Unicode objects despite ASCII-encoded text sources. Certain libraries demand string objects, causing compatibility issues.
To resolve this in Python 2, consider using PyYAML as an alternative JSON parser:
<code class="python">import yaml json_str = '["a", "b"]' data = yaml.safe_load(json_str)</code>
Results:
['a', 'b'] # String objects
Notes:
Conversion:
If you can't guarantee ASCII values, use a conversion function to ensure string objects:
<code class="python">def to_str(obj): if isinstance(obj, unicode): return str(obj) elif isinstance(obj, list): return [to_str(item) for item in obj] elif isinstance(obj, dict): return {to_str(key): to_str(value) for key, value in obj.items()} else: return obj data = json.loads(json_str, object_hook=to_str)</code>
The above is the detailed content of How to Convert JSON Data to String Objects in Python 2?. For more information, please follow other related articles on the PHP Chinese website!