在python中捕获CSV的JSON响应时出错

gupuwyp2  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(168)

无法将所有JSON结果捕获到CSV。

UsergroupURL = "https://" + Test + "3ds.com"
select_params = "select=title,description,owner,members,pending_members,creation_date,modification_date"
skip_value = 0
data = {}
while True:
    UsergroupsURL = UsergroupURL + f"/v1.00/usersgroup?{select_params}&top=100&skip={skip_value}"
    usergroupresponse = session.get(UsergroupsURL, data=data)
    if usergroupresponse.status_code != 200:
        Failmsg = "Failed to retrieve usergroup. Status code: " + str(usergroupresponse.status_code)
        sys.exit(Failmsg)

    results = usergroupresponse.json()
    results = json.loads(usergroupresponse.text)
    print(results)
    if not results:
        break
    
    #Print the results for this iteration
    for row in results:
        print(row)
    
    # Write the results to a CSV file
    csv_filename = f"response_{skip_value}.csv"
    with open(csv_filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(["title", "description", "owner", "members", "pending_members", "creation_date", "modification_date"])
        for result in results:        
            if isinstance(result, dict):
                row = [result.get("title"), result.get("description"), result.get("owner"), result.get("members"), result.get("pending_members"), result.get("creation_date"), result.get("modification_date")]
                row = result.split(',')
                #writer.writerow(row)
            else:
                print("Error: result is not a dictionary")
            #row = result.split(',')                
            row = [
                    result.get("title"), 
                    result.get("description"), 
                    result.get("owner"), 
                    result.get("members"), 
                    result.get("pending_members"), 
                    result.get("creation_date"), 
                    result.get("modification_date")
            ]
            writer.writerow(row)
 
    # Increment the skip value by 100
    skip_value += 100`

以上代码的输出

title,description,owner,members,pending_members,creation_date,modification_date
g,r,o,u,p,s

我希望所有的JSON响应都应该被捕获到CSV中

我的json响应如下:

{
"groups": \[
    {
        "uri": "uuid:uuid1",
        "title": "ADMIN_CS",
        "description": "description1",
        "owner": "test.ferrer@abcd.com",
        "creation_date": "2021-09-10T14:42:04.443Z",
        "modification_date": "2023-03-17T13:15:22.287Z",
        "members": \[
            "member1",
            "member2",
            "member3",
        \],
        "pending_members": \[\]
    },
    {
        "uri": "uuid:uuid2",
        "title": "ADMIN_CS",
        "description": "description1",
        "owner": "test.ferrer@abcd.com",
        "creation_date": "2021-09-10T14:42:04.443Z",
        "modification_date": "2023-03-17T13:15:22.287Z",
        "members": \[
            "member1",
            "member2",
            "member3",
        \],
        "pending_members": \[\]
    },
    {
        "uri": "uuid:uuid3",
        "title": "ADMIN_CS",
        "description": "description1",
        "owner": "test.ferrer@abcd.com",
        "creation_date": "2021-09-10T14:42:04.443Z",
        "modification_date": "2023-03-17T13:15:22.287Z",
        "members": \[
            "member3",
            "member2",
            "member3",
        \],
        "pending_members": \[\]
    },
k5ifujac

k5ifujac1#

我认为你可能把你的编写步骤变得过于复杂了。如果你需要做的只是转换.groups数组中的对象,那么你可以替换这个:

# Write the results to a CSV file
csv_filename = f"response_{skip_value}.csv"
with open(csv_filename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(["title", "description", "owner", "members", "pending_members", "creation_date", "modification_date"])
    for result in results:        
        if isinstance(result, dict):
            row = [result.get("title"), result.get("description"), result.get("owner"), result.get("members"), result.get("pending_members"), result.get("creation_date"), result.get("modification_date")]
            row = result.split(',')
            #writer.writerow(row)
        else:
            print("Error: result is not a dictionary")
        #row = result.split(',')                
        row = [
                result.get("title"), 
                result.get("description"), 
                result.get("owner"), 
                result.get("members"), 
                result.get("pending_members"), 
                result.get("creation_date"), 
                result.get("modification_date")
        ]
        writer.writerow(row)

用这个:

# Write the results to a CSV file
csv_filename = f"response_{skip_value}.csv"
with open(csv_filename, 'w', newline='') as csvfile:
    writer = csv.writer(csvfile)
    header = ["title", "description", "owner", "members", "pending_members", "creation_date", "modification_date"]
    writer.writerow(header)
    for group in results['groups']:
        writer.writerow(group[x] for x in header)

这段代码使用了generator expressions来简化你使用的很多循环,我还将标题行提取到它自己的变量中,这样你就可以修改header,而不需要修改任何其他代码。

相关问题