Home  >  Article  >  Backend Development  >  How to Convert JSON Data to String Objects in Python 2?

How to Convert JSON Data to String Objects in Python 2?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 06:38:29256browse

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:

  • PyYAML returns string objects for ASCII-encoded data, but Unicode objects for Unicode-encoded data.
  • Use yaml.safe_load() for JSON files.
  • For more support with YAML 1.2 and low number parsing, use Ruamel YAML.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn