使用 nodejs var 作为 json object 语句?
use nodejs var as json object statement?
如何在 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”,但它解释为改为“输入”
访问变量键的括号应该可以工作
function myFunction(TYPE){
return(json[TYPE][0])
}
在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
如何在 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”,但它解释为改为“输入”
访问变量键的括号应该可以工作
function myFunction(TYPE){
return(json[TYPE][0])
}
在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