0

I've been banging my head against a wall with this all day, I've looked at other questions and they all say use JSON.parse or something similar, but I can't get anything to work for the life of me.

I have an object stored as text in a PostGres DB:

{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}

I have to read it into a variable and go through it's properties but i can't get it to work, if I do a JSON.parse I get a "SyntaxError: Unexpected number" on the first number {1...}.

I tried looking at the object properties without doing a parse to test it, but it keeps saying it doesn't have that property (with and without ' around the number in case):

if(selectedItems.hasOwnProperty(149804)){
    console.log("HAS 149804");
}else{
    console.log("DOESN'T HAVE 149804");
};

What am I doing wrong here?

2
  • You data might already be in JSON/object format. You can confirm by console.log the variable or console.log(typeof VARIABLE_NAME). Commented Dec 23, 2015 at 0:27
  • you can eval(0|| ... ) it instead of JSON.parse(...), but it will be slightly slower. if you don't fill the database, then be careful using eval. you can probably also use a RegExp to "fix" the JSON into something that can be parse()ed. Commented Dec 23, 2015 at 1:59

2 Answers 2

2

That's because your JSON is invalid.

{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}

should instead be

{"149804": [75319, 2887526, 2938701],"3136977": [3482061,3482062]}

Then JSON.parse will work. Object properties should be strings, not numbers.

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

Comments

1

A key name/index in JSON must be a string. Proper JSON would be:

{
  "149804": [
    75319,
    2887526,
    2938701
  ],
  "3136977": [
    3482061,
    3482062
  ]
}

Comments

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.