[英]Storing objects in JSONB column using Postgres/Knex
I created a graphs table on my back end to store graph related data.我在后端创建了一个图表来存储图表相关数据。 Here is the schema from the Knex migration file:
这是 Knex 迁移文件中的架构:
exports.up = function(knex) {
return (
knex.schema
.createTable('users', tbl => {
tbl.increments();
tbl.string('username', 255).notNullable();
tbl.string('password', 255).notNullable();
tbl.string('name', 255).notNullable();
tbl.string('email', 255).unique().notNullable();
})
.createTable('graphs', tbl => {
tbl.increments();
tbl.string('graph_name', 255).notNullable();
tbl.jsonb('graph_info').notNullable();
tbl
.integer('user_id')
.unsigned()
.notNullable()
.references('id')
.inTable('users')
.onDelete('CASCADE')
.onUpdate('CASCADE');
})
)
};
Here is an example of the type of data that I am trying to store in the jsonb column in my database:以下是我尝试存储在数据库的 jsonb 列中的数据类型示例:
{
labels: ['Axis1', 'Axis2', 'Axis3'],
datasets: [
{
label: 'Dataset1',
borderDash: [0, 0],
backgroundColor: '#fff',
data: [25, 14, 22],
},
],
title: 'Graph1',
}
Now here is the request that I tried to send through Postman:现在这是我尝试通过 Postman 发送的请求:
{
"graph_name": "test10",
"graph_info": "{
labels: ['Axis1', 'Axis2', 'Axis3'],
datasets: [
{
label: 'Dataset1',
borderDash: [0, 0],
backgroundColor: '#fff',
data: [25, 14, 22],
},
],
title: 'Graph1'
}",
"user_id": "1"
}
I received the following error: SyntaxError: Unexpected token in JSON at position 44
.我收到以下错误:
SyntaxError: Unexpected token in JSON at position 44
。 I came across this article when I was trying to figure out what is going on:当我试图弄清楚发生了什么时,我偶然发现了这篇文章:
sending nested json object using postman 使用邮递员发送嵌套的 json 对象
I have my Content-Type header set to application/json
, and Postman isn't giving me a signal that I'm sending a bad request.我的 Content-Type 标头设置为
application/json
,邮递员没有给我一个信号,表明我正在发送一个错误的请求。 I'm not sure what the problem is.我不确定问题是什么。
It's also possible that I'm thinking about this the wrong way.我也有可能以错误的方式思考这个问题。 When I was looking at the Postgres docs, it seemed to me that the best way to store the type of object that I'm trying to store would be with a jsonb column.
当我查看 Postgres 文档时,在我看来,存储我要存储的对象类型的最佳方法是使用 jsonb 列。 But if that is not the case, I'm open to suggestions.
但如果情况并非如此,我愿意接受建议。 Any help would be greatly appreciated.
任何帮助将不胜感激。
From the look of graph_info
in the result, it is not a valid JSON, but a string that contains js object.从结果中的
graph_info
来看,它不是一个有效的JSON,而是一个包含js对象的字符串。
When you saves your data to the JSONB column, you need to apply the JSON.stringify
method on the object.将数据保存到 JSONB 列时,需要对对象应用
JSON.stringify
方法。
For example like this:例如像这样:
{
"graph_name": "test10",
"graph_info": JSON.stringify({
labels: ['Axis1', 'Axis2', 'Axis3'],
datasets: [
{
label: 'Dataset1',
borderDash: [0, 0],
backgroundColor: '#fff',
data: [25, 14, 22],
},
],
title: 'Graph1'
}),
"user_id": "1"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.