You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用字符串变量访问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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:06:02