如何解析多行JSON响应以精确确定特定键的值?

时间:2019-08-07 11:41:23

标签: javascript json jsonparser

我正在尝试解析多行JSON响应,以使用JavaScript获取键的值。我读到我们无法解析多行json,如何实现从json下面获取“ Created”值?

  1. 我尝试将JSON转换为字符串,并使用replace将\ n作为分隔符将多行转换为单行。 -无法替换多行文字。

  2. 我尝试提取恶作剧键值的索引并从字符串中删除-语法错误。

    var v1 =  {
        "data": {
            "type": "articles",
            "id": "1",
            "attributes": {
                "title": "JSON:API paints
    my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            },
            "relationships": {
                "author": {
                    "data": {
                        "id": "42",
                        "type": "people"
                    }
                }
            }
        }
    };
    alert(result.data.attributes.created);
    

我的期望是得到2015-05-22T14:56:29.000Z作为输出。

2 个答案:

答案 0 :(得分:1)

在您的示例中,我看到语法错误

尝试将字符串定义“”更改为“

var v1 =  {
    "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
            "title": `JSON:API paints
my bikeshed!`,
            "body": "The shortest article. Ever.",
            "created": "2015-05-22T14:56:29.000Z",
            "updated": "2015-05-22T14:56:28.000Z"
        },
        "relationships": {
            "author": {
                "data": {
                    "id": "42",
                    "type": "people"
                }
            }
        }
    }
};

console.log(v1.data.attributes.created)

答案 1 :(得分:0)

  • 如果有新行,您可以替换所有新行,然后解析 JSON。
  • 每个操作系统都需要生成不同的换行符 替换换行符时要注意这一点。

var v1 =  `{
    "data": {
        "type": "articles",
        "id": "1",
        "attributes": {
            "title": "JSON:API paints
my bikeshed!",
            "body": "The shortest article. Ever.",
            "created": "2015-05-22T14:56:29.000Z",
            "updated": "2015-05-22T14:56:28.000Z"
        },
        "relationships": {
            "author": {
                "data": {
                    "id": "42",
                    "type": "people"
                }
            }
        }
    }
}`;

var result = v1.replace(/(?:\r\n|\r|\n)/g, '');

var resultObj = JSON.parse(result);

console.log(resultObj.data.attributes.created);