Search code examples
node.jsjsobject

Create string key to a complicated json path


I need to access and conduct a series of operations on a big json object. Some things I need to read and alter are very deep into the tree with paths such as:

result.project.properties[0]['hudson.model.ParametersDefinitionProperty'][0].parameterDefinitions[0]['hudson.model.BooleanParameterDefinition']

This path is something that I will reference over and over. I'd like to be able to do something like:

key = "project.properties[0]['hudson.model.ParametersDefinitionProperty']  [0].parameterDefinitions[0]['hudson.model.BooleanParameterDefinition']"

so I can then read and or write to the path like this:

result[key]

but node doesn't even work with:

result['project.properties']

much less the entire deep path I have to use.

Is there a good way to make the path reusable without having to type the whole thing out more than once?


Solution

  • result[key] refers to an object (key), which you initialized as:

    key = "project.properties[0]['hudson.model.ParametersDefinitionProperty']  [0].parameterDefinitions[0]['hudson.model.BooleanParameterDefinition']"
    

    In your JSON object, there is no object with that large name, so it doesn't work. If you want to not type out that whole thing, try this:

    shortResult = result.project.properties[0]['hudson.model.ParametersDefinitionProperty'][0].parameterDefinitions[0]['hudson.model.BooleanParameterDefinition'];
    

    From here you can access things which are inside "BooleanParameterDefinition".