[英]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. 我整天都在撞墙,我看了其他问题,他们都说使用JSON.parse或类似的东西,但是我一辈子都无法工作。
I have an object stored as text in a PostGres DB: 我有一个对象以文本形式存储在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...}. 我必须将其读取到变量中并通过其属性,但是如果使用JSON.parse,则我在第一个数字{1 ...}上会收到“ SyntaxError:Unexpected number”(语法错误:意外的数字),因此无法正常工作。
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? 我在这里做错了什么?
That's because your JSON is invalid. 那是因为您的JSON无效。
{149804: [75319, 2887526, 2938701],3136977: [3482061,3482062]}
{149804:[75319、2887526、2938701],3136977:[3482061,3482062]}
should instead be 相反应该是
{"149804": [75319, 2887526, 2938701],"3136977": [3482061,3482062]}
{“ 149804”:[75319、2887526、2938701],“ 3136977”:[3482061,3482062]}
Then JSON.parse will work. 然后JSON.parse将起作用。 Object properties should be strings, not numbers.
对象属性应该是字符串,而不是数字。
A key name/index in JSON must be a string. JSON中的键名/索引必须是字符串。 Proper JSON would be:
正确的JSON将是:
{
"149804": [
75319,
2887526,
2938701
],
"3136977": [
3482061,
3482062
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.