0

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 Answer 1

1

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"
}
Sign up to request clarification or add additional context in comments.

1 Comment

I have updated the original question got another issue it has stripped some

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.