简体   繁体   English

如果键名是变量值,则通过json键获取json值

[英]Get json value by json key if the key name is variable value

I have json string and want to get a value by key, but key name is value of some variable. 我有json字符串,想通过键获取值,但是键名是某个变量的值。 To resolve the issue I've found this 为了解决这个问题,我发现了这个

window[varName]

and tried to use as following 并尝试如下使用

<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>

but I get the error 但是我得到了错误

Uncaught TypeError: Cannot read property 'someProperty' of undefined 未捕获的TypeError:无法读取未定义的属性'someProperty'

If I try 如果我尝试

console.log(jsonObj[window[propAsString]]);
console.log(jsonObj[window[propAsString]+'AndSuffix']);

I get two undefined 我得到两个undefined

Remove window and it will work. 删除window ,它将起作用。 jsonObj would be accessible on window ( window.jsonObj ) as javascript is hoisting the assignments with var to the closest scope (in this case the window). jsonObj可以在windowwindow.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']); 

I'm not sure if I correctly understand this, but this is how to solve this: 我不确定我是否正确理解这一点,但这是解决此问题的方法:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM