1

I have a string as below

"{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}" 

How can I actually convert this string to a dictionary? The string originate from a txt file

2
  • 3
    json.loads Commented Jul 3, 2020 at 1:15
  • 1
    ast.literal_eval(..) will also work. Just depends what you're doing. This is useful if you have a column of dict strings in a dataframe. Commented Jul 3, 2020 at 1:20

1 Answer 1

2

You should use the json module. You can either open the file and use json.load(file) or include the text as a string in your program and do json.loads(text). For example:

import json with open('file.txt', 'r') as file: dict_from_file = json.load(file) 

or

import json text = '{"V":1,"Batch":10001,"File":"abc.csv","ContactorID":"A001"}' dict_from_text = json.loads(text) 

For more info see https://realpython.com/python-json/.

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.