Home > Backend Development > Python Tutorial > How to Retrieve String Objects from JSON in Python 2?

How to Retrieve String Objects from JSON in Python 2?

Barbara Streisand
Release: 2024-11-02 23:49:30
Original
353 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template