This question already has answers here:
Convert a String representation of a Dictionary to a dictionary
(11 answers)
How to convert JSON data into a Python object?
(33 answers)
Closed 2 years ago.
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
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/.
Related
This question already has answers here:
How can I parse (read) and use JSON?
(5 answers)
Closed 2 years ago.
So I have a text file with the text below:
{'Maps': {'Usefulness':80,'Accesibility':70,'Popularity':90}
(the dictionary carries on that's why there may be a few syntax issues)
How do I convert this text into python code inside my program?
eg:
if the text files name is x.txt
textfile = convert(x.txt)
print(list(textfile.keys()))
the output would look something like
['Maps','Drive','Chrome']
You can use ast.literal_eval to evaluate a string (like the one you get from reading a text file) as Python code:
import ast
s = """{
'Maps': {
'Usefulness':80,
'Accesibility':70,
'Popularity':90
}
}"""
ast.literal_eval(s)
# output: {'Maps': {'Usefulness': 80, 'Accesibility': 70, 'Popularity': 90}}
Reading from a text file:
with open('file.txt', 'r') as file:
result = ast.literal_eval(file.read())
print(list(result.keys()))
If your text file is just a dictionary you can also use the json module. But the more generalist answer is to use ast.literal_eval.
You should use the json module
import json
with open('x.txt') as json_file:
data = json.load(json_file)
print(data.keys)
This question already has answers here:
Reading JSON from a file [duplicate]
(7 answers)
Closed 3 years ago.
I've been stuck on this for like an hour and I just can't find my mistake even though it has to be somewhere since I know json.load loads the json file into the dictionary and json.dump copies the dictionary to the .json file
p.s the dump does work but the load returns an empty dict
I tried to read the file conventionally and then use the .loads function, did the same thing
prefix = json.load(open('file.json', 'r'))
print("Prefixes currently are:"+str(prefix)) # prints {} even though the file includes : {"551475283459309599": "!", "557678616054464512": "!", "558760765348249609": "!", "559361893861556240": "%"}
I expected it to just do what it should (load the dict or a string or something but it loads nothing)
I tried running it on a different python project and it worked for some odd reason so the problem is probably somewhere else, thanks regardless!!
Try following the way to load json file:
import json
with open('file.json') as json_data:
d = json.load(json_data)
print("Prefixes currently are:"+str(d))
This question already has answers here:
Convert regular Python string to raw string
(12 answers)
Closed 3 years ago.
I am facing with the following error while reading json from file
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 2 column 1 (char 948)
The json content is read from file using the script below
import json
if __name__ == "__main__":
file_path = "D:\\Freelancing\\Scraping_football_historic_data\\Data\\1.138103502"
with open(file_path,'r') as datafile:
dict_data = json.load(datafile)
print(dict_data)
Upon searching for answer, this question had an answer that suggested me to add r before the json string.
How can it be done in the case above, or if there's a better way to read the file. ?
The contents of the file can be read from the pastebin link:
https://pastebin.com/ZyyrtcZW
You are missing a comma between each of your individual dictionaries, your data should look like
....
{"op":"mcm","clk":"5733948534","pt":1514206953689,"mc":[{"id":"1.138103502","rc":[{"ltp":2.02,"id":48756}]}]},
{"op":"mcm","clk":"5739085003","pt":1514309273736,"mc":[{"id":"1.138103502","rc":[{"ltp":2.0,"id":48756}]}]},
{"op":"mcm","clk":"5739711407","pt":1514327265235,"mc":[{"id":"1.138103502","rc":[{"ltp":2.06,"id":48756}]}]},
.....
This question already has an answer here:
Read the written list of dictionaries from file in Python
(1 answer)
Closed 3 years ago.
I'm trying to get from a text file the dictionaries stored in a list
I searched for a json function, which can separate the string and save it in a list (a list of dictionaries), but I do not know if there is something like this.
txt:
[{"Principal": ["Jhon","Anderson","40"]}, {"Secretary": ["Marie","Garcia","29"]},{"Councilor": ["Alan", "Smith","33"]}]
py code:
stringvar=textfile.read()
// for or function below
dictionaries=json.loads(textfile.read())
otherlist=dictionaries
If you wish to load the list of dictionaries from a txt file in Python, you can do it using the literal_eval function from the ast module, in order to evaluate the expression of the string in the file:
import ast
data = []
with open("data.txt", "r") as inFile:
data = ast.literal_eval(inFile.read())
First of all those kind of files are called json files.
You can open and read them as:
import json
f = open("results/results.json")
data = json.load(f)
Square brackets in json file defines an array, while curl brackets an object. The former will be converted to a list in python, the latter to dictionary.
So in your case data will be a list of dictionaries.
You can get the values and keys with the methods of the dictionary class keys(), values() or to get both items().
To be complete a the elements of your json should have the same structure, the fields only should change. For example considering one element:
{"role" : "Principal",
"name: : "Jhon",
"surname. : "Anderson",
"age": 40}
In this way you can iterate more easily through your json
This question already has answers here:
Writing Unicode text to a text file?
(8 answers)
Closed 6 years ago.
I try to write to txt file list with russian string.(I get that with unique1 = np.unique(df['search_term']), it's numpy.ndarray)
thefile = open('search_term.txt', 'w')
for item in unique1:
thefile.write("%s\n" % item)
But in list this string looks correct. But after writing it looks like
предметов berger bg bg045-14 отзывы
звезд
воронеж
Why a get that?
Try writing to the file like this:
import codecs
thefile = codecs.open('search_term.txt', 'w', encoding='utf-8')
for item in unique1:
thefile.write("%s\n" % item)
The problem is that the file likely is encoded correctly hence why the characters will display incorrectly.