如何使用 Javascript 将 JSON 值放入变量中
2022-03-05
53
所以我有这个 JSON:
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "When you win, say nothing. When you lose, say less.",
"length": "51",
"author": "Paul Brown",
"tags": {
"0": "inspire",
"1": "losing",
"2": "running",
"4": "winning"
},
"category": "inspire",
"language": "en",
"date": "2022-03-05",
"permalink": "https://theysaidso.com/quote/paul-brown-when-you-win-say-nothing-when-you-lose-say-less",
"id": "3dlKxoNAOZsB__Nb61H95weF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2024,
"url": "https://theysaidso.com"
}
}
我试图将作者和引文字段中的文本抓取到两个相应的变量中。我已经将变量 JSON 分配给 json 内容。我现在有的是下面不起作用的内容。
QUOTE = JSON.contents.quotes[0].quote;
AUTHOR = JSON.contents.quotes[0].author;
我做错了什么?什么是正确的方法?
2个回答
您是否需要 json 文件?它对我来说很好用。
还要在变量前添加
let
或
var
var json = require('./2.json')
let QUOTE = json.contents.quotes[0].quote;
let AUTHOR = json.contents.quotes[0].author;
console.log(QUOTE, AUTHOR);
此输出为
赢了就别说。输了就少说。Paul Brown
skep_sickomode
2022-03-05
I've already assigned the variable JSON to the json contents.
根据您的解释,我假设您确实将
contents
对象分配给变量
JSON
。在这种情况下,您需要使用
JSON.quotes[0].quote
和
JSON.quotes[0].author
访问属性。请参考以下代码片段。
var yourObject = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "When you win, say nothing. When you lose, say less.",
"length": "51",
"author": "Paul Brown",
"tags": {
"0": "inspire",
"1": "losing",
"2": "running",
"4": "winning"
},
"category": "inspire",
"language": "en",
"date": "2022-03-05",
"permalink": "https://theysaidso.com/quote/paul-brown-when-you-win-say-nothing-when-you-lose-say-less",
"id": "3dlKxoNAOZsB__Nb61H95weF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2024,
"url": "https://theysaidso.com"
}
}
let JSON = yourObject.contents
let yourQuote = JSON.quotes[0].quote
let yourAuthor = JSON.quotes[0].author
console.log(yourQuote)
console.log(yourAuthor)
Deepak
2022-03-05