无法使用 Python BOTO 将语法相同的 json 文件上传到 Amazon SQS

Unable to upload a json file in same syntax to Amazon SQS using Python BOTO

我的 json 文件看起来像:

{
    "id": 1,
    "name": "A green door",
    "price": 12.50,
    "tags": ["home", "green"]
}

我正在使用以下 boto 代码将其上传到 Amazon SQS

import json
import uuid
import time
import boto.sqs
import boto
import glob
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
from boto.sqs.message import RawMessage


def process_file(json_file):
        sqs = boto.sqs.connect_to_region("ap-southeast-1")
        queue = sqs.get_queue("Killswitch")
        with open(json_file) as json_fileone:
                dataone=json.load(json_fileone)
                print dataone
                [queue.write(queue.new_message(i)) for i in dataone]
                print "File sent successfully to queue"

json_files = glob.glob("*json")
for json_file in json_files:
    process_file(json_file)

这段代码工作正常,但是当我通过浏览器上的 AWS 控制台检查我的 SQS 队列时,我看到 4 条消息 而不是这条 json 中包含的一条消息文件..

当我尝试通过 boto 代码阅读相同内容时,我最终收到以下内容:

id 
name 
price 
tags

我需要在一条消息中上传整个文件,而不是作为 4 个对象/消息

是因为这一行:

[queue.write(queue.new_message(i)) for i in dataone]

for i in dataone 表示您正在迭代 json 对象的键

你做得很有效

queue.write(queue.new_message('id')) 
queue.write(queue.new_message('name')) 
queue.write(queue.new_message('price')) 
queue.write(queue.new_message('tags')) 

显然API只接受字符串,你可以试试:

    with open(json_file) as json_fileone:
            dataone=json_fileone.read()
            queue.write(queue.new_message(dataone))
            print "File sent successfully to queue"