Parse JSON properties with reserved words

Some property names are reserved for specific uses (e.g. language, global).
Even if the JSON parsing is correct, using reserved words may return the following response:
TypeError | cannot read property 'global' of undefined.

One way to work around this is to coerce it into a string and use bracket notation.

Example:

jsonData.data.settings.global.language.language_id

Replace the snippet with

jsonData.data.settings['global.language.language_id']

2 Likes

I usually access those using string representation like jsonData.data.settings['global’].language.language_id

However, if response data is not guaranteed to match, then any form of multi level object access (like a.b.c) would error out as cannot find blah of undefined. In such cases, I prefer using _.get(jsonData, β€˜data.settings.global.language.language_id') lodash utility function to do the job for me without raising any error.