Python:限制发布到服务器的json字符串的大小

Python:限制发布到服务器的json字符串的大小,python,json,post,Python,Json,Post,我将数十万条JSON记录发布到一个最大数据上传限制为1MB的服务器上。我的记录可以是非常可变的大小,从几百字节到几十万字节不等 def checkSize(payload): return len(payload) >= bytesPerMB toSend = [] for row in rows: toSend.append(row) postData = json.dumps(toSend) tooBig = tooBig or checkSize

我将数十万条JSON记录发布到一个最大数据上传限制为1MB的服务器上。我的记录可以是非常可变的大小,从几百字节到几十万字节不等

def checkSize(payload):
    return len(payload) >= bytesPerMB 


toSend = []
for row in rows:
    toSend.append(row)
    postData = json.dumps(toSend)
    tooBig = tooBig or checkSize()
    if tooBig:
          sendToServer(postData)
然后将其发布到服务器。它目前可以工作,但是不断地将toSend转储到jsonified字符串似乎真的很重,几乎100%太多了,尽管我似乎找不到另一种方法来完成它。我可以把这些新记录串起来,并把它们放在一起做个记录吗

我相信一定有更干净的方法,但我就是不知道

谢谢你给予的一切帮助


这就是我现在使用的答案,我和下面的@rsegal同时提出了它,只是为了清晰和完整而发布(sendToServer只是一个虚拟函数,用来显示一切正常工作)


我会做如下的事情:

toSend = []
toSendLength = 0
for row in rows:
    tentativeLength = len(json.dumps(row))
    if tentativeLength > bytesPerMB:
        parsingBehavior // do something about lolhuge files
    elif toSendLength + tentativeLength > bytesPerMB: // it would be too large
        sendToServer(json.dumps(toSend)) // don\'t exceed limit; send now
        toSend = [row] // refresh for next round - and we know it fits!
        toSendLength = tentativeLength
    else: // otherwise, it wont be too long, so add it in
        toSend.append(row)
        toSendLength += tentative
sentToServer(json.dumps(toSend)) // if it finishes below the limit

您的解决方案的问题是,从大O的角度来看,它不是很好。我的是线性时间,你的是二次时间,因为你在检查每个循环的累积长度。每次重置postData也不是很有效。

HA!在玩游戏时,我得到了几乎完全相同的解决方案。我有一个“剩余”列表,它接受任何会发送超出限制大小的内容,“toSendLength”应该是“len(json.dumps(toSend))-len(“,”””,“TentiveLength”应该是“len(json.dumps(row))+len(“,”),因为每一行都会添加逗号和空格。谢谢你!事实上,除此之外,我在两个json转储中都添加了“分隔符=(',',':')”,从而节省了更多宝贵的数据!很高兴你成功了!你显然比我更了解Python处理JSON的细节。你似乎又取得了进步,也许这会对将来的人有所帮助。超级冷!
toSend = []
toSendLength = 0
for row in rows:
    tentativeLength = len(json.dumps(row))
    if tentativeLength > bytesPerMB:
        parsingBehavior // do something about lolhuge files
    elif toSendLength + tentativeLength > bytesPerMB: // it would be too large
        sendToServer(json.dumps(toSend)) // don\'t exceed limit; send now
        toSend = [row] // refresh for next round - and we know it fits!
        toSendLength = tentativeLength
    else: // otherwise, it wont be too long, so add it in
        toSend.append(row)
        toSendLength += tentative
sentToServer(json.dumps(toSend)) // if it finishes below the limit