TypeError:WorkItem类型的对象不可JSON序列化 [英] TypeError: Object of type WorkItem is not JSON serializable

查看:113
本文介绍了TypeError:WorkItem类型的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下脚本后,我收到此错误.我想通过此脚本中生成的结果创建一个json文件.我该怎么做才能解决此问题?

I received this error after running the script below. I would like to create a json file through the result that is generated in this script. What can I do to correct this problem?

我尝试通过API进行操作,但无法从此DevOps表中获取所需的字段.

I tried to do it via API but I couldn't get the fields I need from this DevOps table.

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
from azure.devops.v5_1.work_item_tracking.models import Wiql
import json

token = 'xxx'
team_instance = 'https://dev.azure.com/xxx'

credentials = BasicAuthentication("", token)
connection = Connection(base_url=team_instance, creds=credentials)

def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file)

wit_client = connection.clients.get_work_item_tracking_client()

def get_TC_from_query(query):
    query_wiql = Wiql(query=query)
    results = wit_client.query_by_wiql(query_wiql).work_items
    # WIQL query gives a WorkItemReference => we get the corresponding WorkItem from id
    work_items = (wit_client.get_work_item(int(result.id)) for result in results)
    print_work_items(work_items)

get_TC_from_query(
    """\
SELECT *
FROM workitems
WHERE
        [System.TeamProject] = 'xxx'
        and [System.WorkItemType] = 'Product Backlog Item'
        and [System.State] = 'Done'
ORDER BY [System.ChangedDate] DESC
"""
)    

TypeError:WorkItem类型的对象不可JSON序列化

TypeError: Object of type WorkItem is not JSON serializable

推荐答案

灵感来自

Inspired by the thread provided by @jordanm. You can override the default() method to serialize additional types.

我对您的代码进行了以下更改,并且在我测试时可以正常工作.

I made below changes to your code, and it worked when i tested.

首先将work_items列为列表:

First make work_items a list:

work_items = [wit_client.get_work_item(int(result.id)) for result in results]

然后在print_work_items方法中,我用default = lambda o: o.__dict__覆盖json.dump()中的default方法.请检查以下内容:

Then in print_work_items method, i override the default method in json.dump() with default = lambda o: o.__dict__. Please check below:

def print_work_items(work_items):
    for work_item in work_items:
        with open('teste_project.json', 'w') as json_file:
            json.dump(work_items, json_file, default = lambda o: o.__dict__, sort_keys=True, indent=4)

这篇关于TypeError:WorkItem类型的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆