简体   繁体   中英

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

If I try

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

I get two undefined

Remove window and it will work. 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).

 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']) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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