在Python中发布JSON数据

2024-04-20 03:26:42 发布

您现在位置:Python中文网/ 问答频道 /正文

def post():
    url = "someurl.com"
    with open(jsonfile) as myfile:
        for line in myfile:
            post_fields = line
            print(post_fields)
            request = Request(url, urlencode(post_fields).encode())
            json = urlopen(request).read().decode()
            print(json)


post()

我正在尝试使用上面的代码将我的JSON数据发布到一个网站。然而,我遇到了一个错误。错误是

not a valid non-string sequence or mapping object

下面是我的JSON数据。你知道吗

[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]

对我有什么帮助或建议吗?你知道吗


Tags: 数据httpscomjsonurlfieldsrequestcount
2条回答
def post():
    url = "someurl.com"
    with open(jsonfile) as myfile:
        for line in myfile:
            json_data = json.loads(line)
    response = requests.post(url, data=json.dumps(json_data))
    print(response.status_code, response.reason)

post()

我试着把我在网上看到的方法结合起来,这对我来说终于奏效了。你知道吗

以下是我的意见:

  • 您需要精确地确定要发布到url的有效负载部分是什么。你知道吗
  • 您需要使用json.loads对每一行的json对象进行解码

根据您对我问题的回答,json文件包含以下内容。你知道吗

[{"ContentUrl": "https://twitter.com/realDonaldTrump/status/871331574649901056", "Text": "Do you notice we are not having a gun debate right now? That's because they used knives and a truck!", "PublishDate": "4:43 AM - 4 Jun 2017", "Title": "", "SourceUrl": "https://twitter.com/@realDonaldTrump", "SocialNetwork": "Twitter", "Source": "", "Author": "Donald J. Trump", "Like_count": "147,875 likes", "Replies_count": "57,397 replies", "Retweets_count": "45,500 retweets", "Schema": "SOCIAL_MEDIA"}]

那么,您希望在post请求中使用字典的哪个部分作为有效负载呢?你知道吗

这是固定密码。但是您仍然需要精确地确定要使用的urlpayload的正确位置。你知道吗

from urllib import urlencode
from urllib import urlopen
from requests import Request
import json
import requests

def post(jsonfile):
    with open(jsonfile) as myfile:
        for line in myfile:
            # Decoding JSON object
            json_data = json.loads(line)
            # Here you need to iterate over the json_data as it is an array
            for el in json_data:
                url = el["ContentUrl"]
                el.pop("ContentUrl")
                # Here I use the rest of the fields in el as payload
                # But I don't think that you are using the right data
                # You still need to find out which payload you want to send in the post request
                response = requests.post(url, data = el)
                print(response.status_code, response.reason)

jsonfile='testfile.json'
post(jsonfile) 

相关问题 更多 >