Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将javascript dict读入Python_Javascript_Python - Fatal编程技术网

将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。