【问题标题】:Parsing JSON into python without API [duplicate]在没有 API 的情况下将 JSON 解析为 python [重复]
【发布时间】:2019-06-15 15:54:06
【问题描述】:

我正在尝试将 JSON 导入我的 python 脚本,但它似乎不起作用。

我已经尝试了我能想到的一切。我真的不知道还有什么可以尝试的,任何提示都是appriciated

   jsonfile = 'D://python//tracker4R101-master//firefly- 
   master//countr_phonecode.json'
   dial_json = json.loads(jsonfile)
   dial_code = dial_json['dial_code']
   country_code = obj['country_code']

我希望输出类似于

  • 拨号代码:(拨号代码)

错误信息是:

json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

如果您需要更多代码或解释,请告诉我,我很少在 stackoverflow 上发帖,所以我不知道要提供什么信息

【问题讨论】:

    标签: python json


    【解决方案1】:

    json.load 和 'json.loads. loadlets you pass a file like object, whileloads` 有两个函数可以让你传递一个 json 编码的字符串。

    所以如果你想从一个文件中读取你的代码应该是这样的:

        jsonfile_path = 'D://python//tracker4R101-master//firefly-master//countr_phonecode.json'
    
        # open the file
        with open(jsonfile_path, 'r') as jsonfile:
            dial_json = json.load(jsonfile)
    
        dial_code = dial_json['dial_code']
        country_code = obj['country_code']
    

    您还可以读取文件对象并将字符串(如 json 对象)传递给库:

        jsonfile_path = 'D://python//tracker4R101-master//firefly-master//countr_phonecode.json'
    
        # open the file and read its contents
        with open(jsonfile_path, 'r') as jsonfile:
            jsonfile_contents = jsonfile.read()
    
        dial_json = json.loads(jsonfile_contents)
        dial_code = dial_json['dial_code']
        country_code = obj['country_code']
    
    

    https://docs.python.org/2/library/json.html#json.load

    【讨论】:

    • 谢谢,它消除了错误。但现在我得到了一个新的。 TypeError:列表索引必须是整数或切片,而不是 str。错误来自第 50 行: dial_code = dial_json['dial_code']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-27
    • 2012-03-23
    • 2019-11-16
    • 1970-01-01
    • 2022-06-20
    • 2018-06-02
    相关资源
    最近更新 更多