Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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
用Python解码json数据_Python_Json - Fatal编程技术网

用Python解码json数据

用Python解码json数据,python,json,Python,Json,这是我的json数据 { "Chromatic Dragon": "D", "Croesus": "@", "Cyclops": "H", "Dark One": "@", "Death": "&", } 这是我用来解码成dict的代码 import sys, json d = json.loads('mapping.json', encoding='utf-8') print(d) 我希望变量d是dict 但这是我得到的错误 json.decoder.JSOND

这是我的json数据

{
  "Chromatic Dragon": "D",
  "Croesus": "@",
  "Cyclops": "H",
  "Dark One": "@",
  "Death": "&",
}
这是我用来解码成dict的代码

import sys, json
d = json.loads('mapping.json', encoding='utf-8')
print(d)
我希望变量d是dict

但这是我得到的错误

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
有人能帮我吗。

如果json是一个字符串,例如

json = "{
  "Chromatic Dragon": "D",
  "Croesus": "@",
  "Cyclops": "H",
  "Dark One": "@",
  "Death": "&",
}"
如果要加载外部json文件,请改用json.load

所以你的代码是

import sys, json
with open('mapping.json') as json_file:
    d = json.load(json_file)
print(d)
加载一个字符串。您需要打开一个文件,并使用json.load读取该文件

尽管您还需要从JSON文件中去掉尾随逗号,以便python可以对其进行解析。

这不起作用,字符串类型不能作为类似文件的对象进行读取。
import sys, json
with open('mapping.json') as f:
    d = json.load(f, encoding='utf-8')
    print(d)