python - 从 s3 存储桶读取多个 json 文件时出现 Json.loads 错误
问题描述
当我手动传递 json 文件作为在 python shell 中加载的关键时,它工作正常。下面的代码
import os
import json
import boto3
import io
import requests
import botocore
bucket_name = 'dev-data'
folder_name = 'raw/test/'
key_source = 'raw/test/extract_api_20200719.json'
s3_client = boto3.client('s3')
json_obj = s3_client.get_object(Bucket=bucket_name, Key=key_source)
json_data = json_obj["Body"].read().decode('utf-8')
print("############################json_data####################### :", json_data )
print("############################json_data_type################## :", type(json_data))
json_dict = json.loads(json_data)
print("############################json_dict####################### :", json_dict )
print("############################json_dict_type ################# :", type(json_dict))
但是,当使用 for 循环从 s3 存储桶中读取 JSON 对象时,出现错误
import os
import json
import boto3
import io
import requests
import botocore
bucket_name = 'dev-data'
folder_name = 'raw/test/'
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(bucket_name)
for obj in bucket.objects.filter(Prefix=folder_name):
print('Object to extract :', obj)
print('obj key: ', obj.key)
s3_client = boto3.client('s3')
json_obj = s3_client.get_object(Bucket=bucket_name, Key=obj.key)
json_data = json_obj["Body"].read().decode('utf-8')
json_dict = json.loads(json_data)
error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
解决方案
中的某些条目在bucket.objects
数据中没有任何 JSON,因此请检查并跳过它们。
for obj in bucket.objects.filter(Prefix=folder_name):
print('Object to extract :', obj)
print('obj key: ', obj.key)
s3_client = boto3.client('s3')
json_obj = s3_client.get_object(Bucket=bucket_name, Key=obj.key)
json_data = json_obj["Body"].read().decode('utf-8')
if not json_data:
print("Skipping empty", obj.key)
continue
json_dict = json.loads(json_data)
推荐阅读
- node-red - Node Red 如何设置属性 msg.complete
- python - 为什么一个 CNN 的 loss 长期减少,然后突然增加?
- javascript - 跳过视频时间滑块 Selenium
- html - 需要将 DIV-2 粘贴在 DIV-1 的底部,然后在悬停时将其隐藏在 DIV-1 下
- chart.js - Chart.js 中的热图/直方图
- javascript - 具有大小限制和最近最少使用 (LRU) 驱逐的 JavaScript localStorage 缓存
- linux-kernel - 哪个版本的linux内核开始支持V4L2 subdev模型?
- azure - 如何在 terraform 上使用 azurerm 提供程序创建 appRoles
- python - 在python中有条件地为文本着色
- php - 如何创建两个相同的 PHP phar-archives