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

How to parse multi-line JSON response to exact a particular key's value?

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

  1. 我尝试将 JSON 转换为字符串,并使用替换将多行转换为单行,并使用 \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。

在你的例子中我看到语法错误

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

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)

  • 如果是新行,你可以替换所有新行,然后解析 JSON。
  • 每个 OS 生成您需要的不同换行符 在替换换行符时要注意这一点。

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);