[英]How do I convert this string into a dict in python?
I have a string that I get from a mongodb export into a csv: Here's an example: 我有一个从mongodb导出到csv的字符串:这是一个示例:
[{"group":"Most Common","id":"00000000000002","name":"HVAC Specialists","name_singular":"HVAC Specialist"},{"group":"Other","id":"00000000001","name":"Hauling \u0026 Junk Removers","name_singular":"Hauling \u0026 Junk Remover"}]
I'm trying to put the date into a dict so I can pull out what I need and export it. 我正在尝试将日期放入字典中,这样我就可以取出需要的内容并将其导出。
I tried putting in into a list, but it created elements out of each letter. 我尝试放入一个列表中,但是它从每个字母中创建了元素。
The string is in a txt file and I'm calling it like this: 该字符串在txt文件中,我这样称呼它:
python stringwork.py thestring.txt
I saw this question and tried this: 我看到了这个问题并尝试了以下操作:
from sys import argv
import json
# filename = argv
txt = open(argv[1])
json.loads(str(txt))
And I got the following error. 我得到了以下错误。
ValueError: No JSON object could be decoded
The txt
variable is a file object and can't be converted to a string. txt
变量是一个文件对象,不能转换为字符串。 So you should read the contents of the file object such as txt = open(argv[1]).readlines()
. 因此,您应该阅读文件对象的内容,例如
txt = open(argv[1]).readlines()
。 Then you can obtain the string in the txt
list with txt[0]
. 然后,您可以使用
txt[0]
在txt
列表中获取字符串。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import argv
import json
filename = argv
txt = open(argv[1]).readlines()
a = json.loads(str(txt[0]))
print(a)
You are a bit confused here: 您在这里有点困惑:
txt = open(argv[1])
json.loads(str(txt))
After this, txt
is a file object, not the actual string. 在此之后,
txt
是文件对象,而不是实际的字符串。
For that you'll need to do something like this: 为此,您需要执行以下操作:
txt = open(argv[1]).read()
json.loads(txt)
Here txt
is already a string with the file content, so there is no need for str
. 这里
txt
已经是包含文件内容的字符串,因此不需要str
。
Do check the documentation on reading / writing files. 请检查文件的读/写文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.