[英]Get json value by json key if the key name is variable value
我有json字符串,想通过键获取值,但是键名是某个变量的值。 为了解决这个问题,我发现了这个
window[varName]
并尝试如下使用
<script>
var jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}';
var jsonObj = JSON.parse(jsonStr);
var propAsString = 'someProperty';
console.log(jsonObj.window[propAsString]);
console.log(jsonObj.window[propAsString]+'AndSuffix');
</script>
但是我得到了错误
未捕获的TypeError:无法读取未定义的属性'someProperty'
如果我尝试
console.log(jsonObj[window[propAsString]]);
console.log(jsonObj[window[propAsString]+'AndSuffix']);
我得到两个undefined
删除window
,它将起作用。 jsonObj
可以在window
( window.jsonObj
)上访问,因为javascript使用var将分配提升到最接近的作用域(在本例中为window)。
var jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}'; var jsonObj = JSON.parse(jsonStr); var propAsString = 'someProperty'; console.log(jsonObj[propAsString]); console.log(jsonObj[propAsString + 'AndSuffix']);
我不确定我是否正确理解这一点,但这是解决此问题的方法:
const jsonStr = '{"someProperty":"Value of someProperty","somePropertyAndSuffix":"Value of somePropertyAndSuffix"}' const obj = JSON.parse(jsonStr) const propAsString = 'someProperty' console.log(obj[propAsString], obj[propAsString + 'AndSuffix'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.