Mankind1023
Mankind1023

Reputation: 7742

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?

Upvotes: 0

Views: 30

Answers (2)

Hatchet
Hatchet

Reputation: 5428

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

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

Upvotes: 1

NGPixel
NGPixel

Reputation: 390

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.

Upvotes: 2

Related Questions