JSON Parsing with a Mix of Single and Double Quote
- Using
json.loads
Method - Using
ast.literal_eval
- Using a Custom Parser
JSON Parsing With A Mix Of Single And Double Quote Using json.loads
Method
In this example, the below code uses the json
module in Python to parse JSON data stored in the json_data
string. The json.loads
the method is employed with strict=False
to accommodate a mix of single and double quotes in the JSON structure.
Python3
import json json_data = '{"name": "John", "age": 30, "city": "New York"}' # Parsing JSON with mixed quotes using json.loads parsed_data = json.loads(json_data, strict = False ) # Accessing parsed data print (parsed_data[ 'name' ]) print (parsed_data[ 'age' ]) print (parsed_data[ 'city' ]) |
John 30 New York
Json Parsing With A Mix Of Single And Double Quote Using ast.literal_eval
In this example, below code uses the ast.literal_eval
function to parse a JSON-like string with mixed quotes into a Python dictionary. It then prints the values associated with the ‘name’, ‘age’, and ‘city’ keys from the parsed data, demonstrating how to access specific elements in the dictionary.
Python3
import ast json_data = '{"name": "John", \'age\': 30, "city": \'New York\'}' # Parsing JSON with mixed quotes using ast.literal_eval parsed_data = ast.literal_eval(json_data) # Accessing parsed data print (parsed_data[ 'name' ]) print (parsed_data[ 'age' ]) print (parsed_data[ 'city' ]) |
John 30 New York
Json Parsing With A Mix Of Single And Double Quote Using a Custom Parser
In this example, code defines a custom JSON parser function (custom_json_parser
) that replaces single quotes with double quotes in a given JSON-like string. It then utilizes json.loads
to parse the modified string into a Python dictionary. Finally, it prints specific values (‘name’, ‘age’, ‘city’) from the parsed data.
Python3
import re import json def custom_json_parser(json_data): # Replace single quotes with double quotes json_data = re.sub(r "\'" , '"', json_data) # Use json.loads for parsing parsed_data = json.loads(json_data) return parsed_data json_data = '{"name": "John", \'age\': 30, "city": \'New York\'}' # Parsing JSON with mixed quotes using a custom parser parsed_data = custom_json_parser(json_data) # Accessing parsed data print (parsed_data[ 'name' ]) print (parsed_data[ 'age' ]) print (parsed_data[ 'city' ]) |
John 30 New York
Parsing JSON with Single and Double Quote in Python
We are given JSON data and we will need to parse JSON data with a mix of single and double quotes. In this article, we will see how to parse JSON data with a mix of single and double quotes.
Example:
Input : '{"name": "John", "age": 30, "city": "New York"}' Output : John 30 New York Explanation : Here, we have JSON data with mix doublw and single quote and we parsing it.