Javascript / Node - Convert json stored as text in DB to JSON object
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?
Answer
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM