0

Say I have a config file in which I have paths to JSON properties. My JSON looks like:

var test = { test: { test2: { test3: 1 } } }

and I have a string str = "test.test2.test3"

I know I can access the top level one like this: var foo = "test", test[foo]

But test["test.test2.test3"] does not work. On the other hand test["test"]["test2"]["test3"] works, but this is not a one liner if I have more complex objects (some can be 5 levels in, some can be 3 etc)

Is there any way to access this property directly instead of splitting on the dot and looping through?

1
  • 2
    That isn't JSON, it is a JavaScript object literal. JSON is a data format based on a subset of JavaScript (which that code does not conform to). Commented Mar 23, 2011 at 21:53

1 Answer 1

4
with(test) eval(str);

Did anyone's head explode?

It's either that or

eval('test.' + str);

Take your pick from the bad practice basket.

Though for the first example if you actually want the value you'd want to do this

var value;
with(test) value = eval(str);

But that kind of takes away from the purity of this bad practice masterpiece.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah thanks, eval completely slipped my mind, for those very reasons. I haven't seen with yet, so that's interesting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.