0

This code returns a str as the type. Given the format of tasks, how do I convert it into a python dictionary?

import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

Note: I would prefer to not use ast.literal_eval or ast.eval.

4
  • 1
    Get rid of the line that calls json.dumps(). Commented Jul 7, 2021 at 23:56
  • 1
    Why don't you want to use ast.literal_eval()? This is precisely what it's intended for. Commented Jul 7, 2021 at 23:57
  • Your code will do the wrong thing for {'None': 'val1'} or {'key1': 'None of us are coming'} Commented Jul 7, 2021 at 23:57
  • Please work through the documentation and/or tutorials for the json package. You have the right idea, but you need to learn the usage idioms. Commented Jul 7, 2021 at 23:59

1 Answer 1

1
import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

# new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

As Barmar said, the dumps double wraps it in quotation marks

output:

<class 'dict'>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.