我正在进行API调用,该调用将在正文中返回JSON,并且我想将JSON对象与String进行比较。我怎样才能做到这一点?

API res.body返回以下JSON对象:

{
    "name": "tenant_tree",
    "documents": [
        {
            "tags": [],
            "scope": "all",
            "tenant_id": "0",
            "id": "9dd2c5a5-2de2-4ac8-b195-04290f83b6fb",
            "version": 1,
            "description": "",
            "name": "0",
            "grouping": "",
            "perm_read": "all",
            "perm_write": "all",
            "version_author": "dg",
            "version_date": 1470324147050,
            "is_current": true,
            "dependencies_guid": [""],
            "dependencies_name": [""],
            "display_name": "system"
        },
 }


我想比较像expect(res.body).toMatch('"name": "0"');这样的东西,但是失败了。

最佳答案

在这里不要在字符串检查中使用字符串比较或子字符串。您正在处理的JSON具有结构和自己的语法规则。比较对象。这是检查与name键对应的值的方法:

var obj = JSON.parse(res.body);
expect(obj.name).toEqual("0");


另外,jasmine-matchers软件包中有一些advanced object matchers,请签出。

09-20 21:19