无法使用json包读取我的json文件

时间:2019-01-09 10:55:45

标签: json python-3.x

我是python3的新手,请尝试从Google云存储桶中读取我的josn文件,如下所示:

Uncaught TypeError: _this2.props.updateHandle is not a function

Uncaught TypeError: _this2.props.removeTask is not a function 

我的json文件如下所示:

try:
    content=#downlaod from blob
    print(content)
    json_application_properties=json.loads(str(content))
except Exception as ex:

但是,我在阅读它时遇到了异常

{
    "application": {
        "project_id": "fiery-bay-224704"
    },
    "ingestion": {
        "fileingestion_mappings": {
            "id":"small-files",
            "input_directory": "gs://small-files/*",
            "staging_directory": "gs://small-files/staging",
            "kafka_topic": "kafkatopic-small-files",
            "big_query_table_name": "bigquery-small-files"
        },
         "fileingestion_mappings": {
            "id":"big-files",
            "input_directory": "gs://small-files/*",
            "staging_directory": "gs://small-files/staging",
            "kafka_topic": "kafkatopic-small-files",
            "big_query_table_name": "bigquery-small-files"
        }
    }
}

有人可以指出为什么发生此错误以及为什么我的JSON文件无效

打印内容如下:

Traceback (most recent call last):
  File "main.py", line 37, in <module>
    gcs_object_insert()
  File "main.py", line 17, in gcs_object_insert
    json_application_properties=json.loads(str(content))
  File "/usr/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

1 个答案:

答案 0 :(得分:1)

您加载的content是一个字节对象-如果不指定编码,则无法将其转换为字符串

bytes_object = b'this is bytes object'
print(str(bytes_object))
>>> b'this is bytes object'

json解析器看到开头“ b”,而不是预期的“ {”

不是使用str(something)转换,而是在字节对象上使用.decode(formatting)(请参见https://docs.python.org/3/library/stdtypes.html#bytes.decode

所以在你的情况下

json_application_properties=json.loads(content.decode('utf-8'))