我正在尝试解析多行JSON响应,以使用JavaScript获取键的值。我读到我们无法解析多行json,如何实现从json下面获取“ Created”值?
我尝试将JSON转换为字符串,并使用replace将\ n作为分隔符将多行转换为单行。 -无法替换多行文字。
我尝试提取恶作剧键值的索引并从字符串中删除-语法错误。
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作为输出。
答案 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)
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);