Parsing JSON with Single and Double Quote in Python
Last Updated :
05 Mar, 2024
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.
JSON Parsing with a Mix of Single and Double Quote
Below, are the methods of JSON parsing with a mix of single and double quotes in Python:
- 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"}'
parsed_data = json.loads(json_data, strict = False )
print (parsed_data[ 'name' ])
print (parsed_data[ 'age' ])
print (parsed_data[ 'city' ])
|
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\'}'
parsed_data = ast.literal_eval(json_data)
print (parsed_data[ 'name' ])
print (parsed_data[ 'age' ])
print (parsed_data[ 'city' ])
|
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):
json_data = re.sub(r "\'" , '"', json_data)
parsed_data = json.loads(json_data)
return parsed_data
json_data = '{"name": "John", \'age\': 30, "city": \'New York\'}'
parsed_data = custom_json_parser(json_data)
print (parsed_data[ 'name' ])
print (parsed_data[ 'age' ])
print (parsed_data[ 'city' ])
|
Share your thoughts in the comments
Please Login to comment...