Remove Quotes from JSON keys in Python

In this tutorial, you will learn various methods to remove quotes from JSON keys in Python.

We’ll explore techniques using built-in Python methods like strip() and the json module, as well as using regular expressions.

 

 

Using strip()

First, let’s consider a sample JSON string:

json_data = '{"customer_id": "12345", "plan": "Premium", "status": "Active"}'

Now, let’s use Python strip() method to remove the quotes from the keys:

import json
json_data = '{"customer_id": "12345", "plan": "Premium", "status": "Active"}'
data = json.loads(json_data)

# Remove quotes from keys
for key in list(data.keys()):
    new_key = key.strip('"') 
    data[new_key] = data.pop(key)

# Convert dict to JSON manually without dumps
json_str = '{'
for key, value in data.items():
    json_str += f'\n   {key}: {json.dumps(value)},'
json_str = json_str[:-1] + '\n}' 
print(json_str)

Output:

{
   customer_id: "12345",
   plan: "Premium",
   status: "Active"
}

First, we parse into dict and remove key quotes. Then we build the JSON string manually by looping through dict items and we use json.dumps() to serialize the values with quotes, but add the keys without quotes.

 

Custom JSON Decoder

Python json module allows you to encode and decode JSON data. Let’s create a custom JSON decoder to handle unquoted keys.

First, import the json module and define your JSON string:

import json
json_data = '{"customer_id": "12345", "plan": "Premium", "status": "Active"}'

Now, let’s define a function that will act as our custom decoder. This function will modify the way Python interprets the JSON keys:

def custom_decoder(json_dict):
    new_dict = {}
    for key, value in json_dict.items():
        new_key = key.replace('"', '')
        new_dict[new_key] = value
    return new_dict
decoded_data = json.loads(json_data, object_hook=custom_decoder)
print(decoded_data)

Output:

{'customer_id': '12345', 'plan': 'Premium', 'status': 'Active'}

In this output, you can see that the keys in the JSON data no longer have quotes.

The custom_decoder function iterates through the key-value pairs in the original JSON, removes the quotes from the keys, and constructs a new dictionary with the modified keys.

The output dictionary is displayed with quotes around them due to the default string representation of dictionaries in Python. However, the keys themselves do not actually contain the quotes.

If you want to confirm that the keys do not contain quotes, you can use the type() function to check the type of the keys. Here’s an example:

import json
json_data = '{"customer_id": "12345", "plan": "Premium", "status": "Active"}'
def custom_decoder(json_dict):
    new_dict = {}
    for key, value in json_dict.items():
        new_key = key.strip('"')
        new_dict[new_key] = value
    return new_dict
decoded_data = json.loads(json_data, object_hook=custom_decoder)
for key in decoded_data:
    print(type(key))

Output:

<class 'str'>
<class 'str'>
<class 'str'>

As you can see from the output, the type of each key is <class 'str'>, confirming that the keys do not contain quotes.

The quotes you see when printing the dictionary are part of the representation of the dictionary and do not indicate the presence of quotes in the keys themselves

 

Using Regular Expressions

First, import the re module and define your JSON string, akin to handling data in a telecom context:

import re
json_data = '{"customer_id": "12345", "plan": "Premium", "status": "Active"}'

Next, use a regular expression pattern to identify and replace the quotes around the keys:

pattern = r'\"(\w+)\":'
cleaned_data = re.sub(pattern, r'\1:', json_data)
print(cleaned_data)

Output:

{customer_id: "12345", plan: "Premium", status: "Active"}

In this output, the quotes around the keys have been successfully removed.

The regex pattern \"(\w+)\": matches any word (\w+) that is surrounded by quotes and followed by a colon.

The re.sub function then replaces this pattern with the word itself (\1 refers to the first captured group in the pattern).

Leave a Reply

Your email address will not be published. Required fields are marked *