将javascript dict读入Python
我有一个文件将javascript dict读入Python,javascript,python,Javascript,Python,我有一个文件file.js,其中包含: Foo.bar={ “键1”:“值1”, “键2”:“值2”, } 我想把这条格言读成Python。我想出了一个好主意 from pathlib import Path import json txt = Path('file.js').read_text() json.loads(txt[txt.find('{'):txt.find('}')+1]) 这感觉有点像黑客——有更好的方法吗 with open('file.js') as json_fi
file.js
,其中包含:
Foo.bar={
“键1”:“值1”,
“键2”:“值2”,
}
我想把这条格言读成Python。我想出了一个好主意
from pathlib import Path
import json
txt = Path('file.js').read_text()
json.loads(txt[txt.find('{'):txt.find('}')+1])
这感觉有点像黑客——有更好的方法吗
with open('file.js') as json_file:
data = json_file.read()
data_dict = eval(data[data.find("=") + 1:])
考虑到您的文件只包含一个json对象,就像您的示例一样。文件.js是否总是包含一个命名对象?您可以使用正则表达式。或者按
=
拆分并使用ast.literal\u eval
为什么不将file.js
制作成一个可以读入两种语言的json文件?@Marc AndréBrochu yes至少应该将find(“}”)设置为rfind以覆盖嵌套该代码将引发异常,因为file.json
中的数据不是有效的jsonEdited,它应该获取“=”后面的数据,并将其存储为dict。