【问题标题】:JSONDecodeError : Extra data: line 2 column 1JSONDecodeError:额外数据:第 2 行第 1 列
【发布时间】:2021-06-28 10:33:55
【问题描述】:

我正在尝试从 S3 存储桶中读取 json 压缩文件并使用 aws lambda 服务写入 dynamo db 表,我选择了 python boto3 语言。读取 s3 数据后,尝试运行 json.loads 时出现此错误。

我的代码看起来像 -

import json
import gzip
import boto3
from io import BytesIO

s3 = boto3.resource('s3')
dynamodb = boto3.resource('dynamodb')

def lambda_handler(event, context):
    bucket = event['Records'][0]['s3']['bucket']['name']
    json_file_name = event['Records'][0]['s3']['object']['key']
    
    json_object = s3.Object(bucket, json_file_name)
    
    n = json_object.get()['Body'].read()
    gzipfile = BytesIO(n)
    gzipfile = gzip.GzipFile(fileobj=gzipfile)
    content = gzipfile.read().decode('utf-8')

    jsonDict = json.loads(content)
    
    # Write items to dynamo db table
    table = dynamodb.Table('mahbis01-AccountService-LedgerSummary-Duplicate')
    table.put_item(Item=jsonDict)
    
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

当我打印 content 时,我看到的值类似于 -

{
   "Item":{
      "SubsId":{
         "S":"255_0_908764"
      }
   }
}{
   "Item":{
      "SubsId":{
         "S":"255_0_908765"
      }
   }
}{
   "Item":{
      "SubsId":{
         "S":"255_0_908766"
      }
   }
}{
   "Item":{
      "SubsId":{
         "S":"255_0_908767"
      }
   }
}

我怎样才能摆脱这个并将数据写入 dynamo db?

【问题讨论】:

    标签: python-3.x amazon-web-services aws-lambda boto3


    【解决方案1】:

    您的content 显然是不正确的 json。假设content 字符串具有常量格式,您可以使用以下方法将其转换为 json:

    jsonDict = json.loads('['+content.replace('}{','},{')+']')
    

    这将为您提供有效的字典列表

    [{'Item': {'SubsId': {'S': '255_0_908764'}}}, {'Item': {'SubsId': {'S': '255_0_908765'}}}, {'Item': {'SubsId': {'S': '255_0_908766'}}}, {'Item': {'SubsId': {'S': '255_0_908767'}}}]
    

    然后你可以迭代它并处理你想要的,例如:

    for item in jsonDict:
      print(item)
      # or upload to dynamodb
    

    【讨论】:

    • 谢谢,我可以得到我想要的结果。但是为什么键/值用单引号引起来而不是怀疑呢?
    • @BiswajitMaharana 它打印为 python dict,而不是 json。如果答案有帮助,我们将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2021-07-13
    • 2020-02-03
    • 2018-06-16
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多