Federico Lenzi
Federico Lenzi

Reputation: 1612

Node.js eval var json parse

I'm trying to make a small parser which receives the json string and the path to get:

var args = process.argv;
var jsonToBeParsed = args[2];
var path = args[3];

var result = JSON.parse(jsonToBeParsed);

console.log(result);
console.log(result.path);

I'm calling this with

node parser.js '{"asd":"123", "qwe":"312"}' 'asd'

It gives me undefined

I think it has to be done with some eval function but I don't have too much experience with node/JS. How can I resolve this?, I need to get the result from the command line.

Edit: I'm expecting "123" in the second log. Thanks @Esailija, the question wasn't too clear ...

Upvotes: 0

Views: 1299

Answers (3)

ThorSummoner
ThorSummoner

Reputation: 18099

I wanted to embed the json parser into a git alias, To get a json node in bash (using node)

node -e "console.log(JSON.parse(process.argv[1]).foo.bar)" '{"foo":{"bar":"Hello World"}}'

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60717

To add to @Esailija's answer:

node parser.js '{"path": "123"}' 'asd'

Would return 123. The dot notation expects the property name. If you have a dynamic property name, you need to use the square brackets notation.

console.log(result['ads']);
// But what you want is:
console.log(result[path]); // 'path' is a variable with the correct string

Upvotes: 2

Esailija
Esailija

Reputation: 140210

I think you are trying to use dynamic property, you cannot use .path, because that literally means .path property.

Try this:

console.log(result);
console.log(result[path]);

if path === "asd", then it will work, which is statically equivalent to result["asd"] or result.asd

Upvotes: 5

Related Questions