最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to compare json object with a string? - Stack Overflow

programmeradmin5浏览0评论

I am making a API call which will return JSON in the body and I want to pare JSON object with a String. How can I do that?

API res.body returns following JSON object:

{
    "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"
        },
 }

I want to pare something like expect(res.body).toMatch('"name": "0"'); but this fails.

I am making a API call which will return JSON in the body and I want to pare JSON object with a String. How can I do that?

API res.body returns following JSON object:

{
    "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"
        },
 }

I want to pare something like expect(res.body).toMatch('"name": "0"'); but this fails.

Share Improve this question edited Aug 8, 2016 at 14:32 NatNgs 87414 silver badges27 bronze badges asked Aug 4, 2016 at 17:01 ssharmassharma 9392 gold badges19 silver badges44 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Don't use string parisons or substring in a string checks here. You are dealing with JSON which has structure and its own syntax rules. Compare objects instead. Here is how you can check the value corresponding to the name key:

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

Also, jasmine-matchers package has some advanced object matchers, check them out.

I am able to pare json values in the API response body by:

expect(res.body.name).toEqual("0")

No need of parsing the response.

Refereed link : JSON.Parse,'Uncaught SyntaxError: Unexpected token o

发布评论

评论列表(0)

  1. 暂无评论