如何使用字符串变量访问JSON文件中的值?
解决通过变量访问JSON对象属性的问题
你当前使用codevalues.str无法获取目标值,是因为点符号.只能用于访问字面量属性名,而你需要用变量str的内容作为属性名,此时必须使用方括号访问语法。
修正后的代码
let str = "awes123"; console.log(`code value codeValueStorage <<`, codevalues[str]);
额外注意事项
确保你已经将codevalues.json正确解析为JavaScript对象:
- Node.js环境:
const codevalues = require('./codevalues.json'); - ES模块环境:
import codevalues from './codevalues.json' assert { type: 'json' }; - 浏览器环境:
fetch('./codevalues.json') .then(res => res.json()) .then(codevalues => { let str = "awes123"; console.log(`code value codeValueStorage <<`, codevalues[str]); });
内容的提问来源于stack exchange,提问作者Rohit Jambhulkar
相关产品推荐
相关产品推荐

