TypeError: Object of type WorkItem is not JSON serializable

TypeError: Object of type WorkItem is not JSON serializable

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

我尝试通过 API 来完成,但我无法从这个 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: Object of type WorkItem is not JSON serializable

下面产生一个generator,JSON无法序列化:

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

您可以改为 work_items 一个列表,JSON 可以序列化:

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

受@jordanm提供的thread启发。您可以覆盖 default() 方法以序列化其他类型。

我对您的代码进行了以下更改,并且在我测试时有效。

First make work_items a list:

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

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)