是否可以在json脚本中使用变量搜索特定元素



脚本为示例。我需要它来记录Joe这个名字;

const names = `
{
"Joe": {
"nat": "American",
"hair": "brown"
},
"Peter": {
"nat": "German",
"hair": "blond"
}
}
`;
const load = JSON.parse(names);
var search = "Joe"
console.log(names.search);

最后一行输出"undefined"因为它在搜索"搜索"而不是变量搜索的值。在你问之前:是的,我需要它是一个变量(因为变量的值实际上是输入的值)。是否有任何方法我可以在JSON位搜索变量的值?

Thanks in advance

差不多了(你还得先解析一下):

const names = `
{
"Joe": {
"nat": "American",
"hair": "brown"
},
"Peter": {
"nat": "German",
"hair": "blond"
}
}
`;
const load = JSON.parse(names);
var search = "Joe"
console.log(load[search]);

尝试使用名称[search]代替

最新更新