1

I am trying to parse JSON that looks like this:

{ "values" : [{ "alpha":8 },{ "beta":4 },{ "gamma":-3 } ]}

I'm parsing it with: console.log(msg.values.alpha), and get:

Missing error handler on `socket`.
TypeError: Cannot read property 'alpha' of undefined

This is how I have seen done it on other sites. Doing it with console.log(msg.values) returns undefined, and just running console.log(msg) returns proper JSON. I have seen other people with this issue, but nothing that is said to do is working. Thanks!

11
  • 1
    Are you running JSON.parse(msg)? Commented Jan 2, 2016 at 5:59
  • No, apparently that is for parsing non JSON text into JSON. @KailanBlanks Is that incorrect? If so what's the syntax? Commented Jan 2, 2016 at 6:00
  • 1
    Assuming that msg is a String with JSON, data = JSON.parse(msg) will parse it into an object. Then you will have to follow what t3dodson said in his answer. Commented Jan 2, 2016 at 6:01
  • So like data = JSON.parse(msg); console.log(data.values[0].alpha);? Commented Jan 2, 2016 at 6:04
  • 1
    most errors in nodejs are due to to scope , confirm that the JSON object has existence before you output it's value . try to check it's length , I guess it has not loaded or some reason like that . Commented Jan 2, 2016 at 6:07

1 Answer 1

2

Don't forget to parse it to an object using JSON.parse

msg.values is an array. Technically you would have to access it via msg.values[0].alpha.

Better solution.

if you are using underscore npm install underscore

var _ = require('underscore');
var msg = JSON.parse('{ "values" : [{ "alpha":8 },{ "beta":4 },{ "gamma":-3 } ]}');
var alpha = _.find(msg.values, function (value) {
    return value.hasOwnProperty('alpha');
}).alpha;

The underscore solution would allow you to not rely on the order of the array so its probably better style.


Here is a fiddle of my code running in a browser.

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

9 Comments

@SkylerSpaeth Please see my update. The snippet I have works if you install underscore.
Ok, I will. Character limit :(
Ok, I'm still getting SyntaxError: Unexpected token C.
@SkylerSpaeth is the JSON you posted in your question the exact same as you tried? I've ran this locally and it worked. I'm making a fiddle right now.
@SkylerSpaeth I've added a link to a fiddle of the above code.
|

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.