【问题标题】:use nodejs var as json object statement?使用 nodejs var 作为 json 对象语句?
【发布时间】:2022-02-07 22:31:25
【问题描述】:

如何在 json 语句中使用 nodejs var,我真的没有必要的词汇来解释,但这是我的简化代码:

test.json:

{
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

test.js:

const json = require("./test.json")
function myFunction(TYPE){
return(json.TYPE[0])
}
console.log(myFunction("test1"))

当我使用“type”变量时,它尝试将其用作 json 语句或对象,但显然没有“type”,只有“test1”和“test2”,但它解释为“type”

【问题讨论】:

标签: node.js json function object var


【解决方案1】:

访问变量键的括号应该可以工作

function myFunction(TYPE){
return(json[TYPE][0])
}

【讨论】:

    【解决方案2】:

    在 JavaScript 中,json 对象与普通的 JS 对象非常相似。您需要使用字符串作为索引来访问属性:

    // This could be your json file, its almost the same
    // Just require it like you did instead of using const JSON like i am
    const json = {
    "test1":["test1.1", "test1.2"],
    "test2":["test2.1", "test2.2"]
    }
    
    function myFunction(TYPE){
    // Access the json by using keyword directly as index string
      return(json[TYPE])
      // because TYPE is a string, TYPE[0] would mean first letter of TYPE string
    }
    
    function myFunctionDeeper(TYPE){
      // To access a field and array in that field
      return(json[TYPE][0])
    }
    
    console.log(myFunction("test1"))
    console.log(myFunctionDeeper("test1"))
    
    // example for what happens when accessing string by index
    console.log("test1"[0])

    阅读更多关于对象here

    【讨论】:

    • 非常感谢,我从没想过使用 2 个 var,我总是尝试像 json[type][0] 或 json[type[0]] 但只是写 2 个 var,比如 type = json[ type] 和 type[0] 工作这花了我这么长时间
    • 没有“json 对象”这样的东西。对 JSON 文件的 Require 将 JSON 解析为 JavaScript 对象。使用正确的术语会有所帮助。
    • @HereticMonkey 我用json对象来引用对象的来源,也就是json文件。抱歉,如果这太混乱了。
    • @HereticMonkey 你是不是因为不懂的术语而改变了正确的答案?
    • @user3133 当您不了解网站的运作方式时,请不要指责他人。我(作为像您一样的用户)无法更改 已接受 答案。只有 OP(提问者)才能做到这一点。另外,我理解术语,我的评论是为了纠正您对术语的错误使用。
    猜你喜欢
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 2015-02-06
    • 1970-01-01
    相关资源
    最近更新 更多