Python:Convert into JSON Format

48 views Asked by At

Requirement: Convert plain text into JSON format

Input:

  data3 =   "{   'type': 'service_account',   'project_id': 'innate-paratext-90872'}"

Expected Output in JSON format:

{
    "type": "service_account",
    "project_id": "innate-paratext-90872"
}

Tried: Method 1

json_str = json.dumps(data3)

output:

"{   'type': 'service_account',   'project_id': 'innate-paratext-90872'}"

Method 2:

json_str = json.loads(data3)

Error:

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 5 (char 4)

EDIT 1: Solution given by Mark Tolonen below works fine but it strips of some as an example below

data3 = "{'type': 'service_account',   'project_id': 'innate-paratext-90872',   'private_key': '-----BEGIN PRIVATE KEY-----\\nMIIEvgIBADANBgkqhkiG9w0BA\\n-----END PRIVATE KEY-----\\n'}",

Expected Output:

"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BA\n-----END PRIVATE KEY-----\n",

Your Code output: (it has striped out "\" in the "\n")

"private_key": "-----BEGIN PRIVATE KEY-----nMIIEvgIBADANBgkqhkiG9w0BAn-----END PRIVATE KEY-----n",
1

There are 1 answers

1
Mark Tolonen On

Your string is in Python source format, so you can use ast.literal_eval to convert it to a true Python dictionary suitable for json.dumps:

>>> s = "{   'type': 'service_account',   'project_id': 'innate-paratext-90872'}"
>>> import ast
>>> d = ast.literal_eval(s)
>>> d
{'type': 'service_account', 'project_id': 'innate-paratext-90872'}
>>> import json
>>> print(json.dumps(d,indent=4))
{
    "type": "service_account",
    "project_id": "innate-paratext-90872"
}