【问题标题】:JSON.parse not working with knex where clause [duplicate]JSON.parse 不适用于 knex where 子句 [重复]
【发布时间】:2021-09-14 03:32:40
【问题描述】:

我正在使用 knex 创建动态删除功能。

编辑:该函数是从 GraphQL 突变中调用的,并且 tableName 和 whereClause 都是字符串。在下面的编辑代码中,我将覆盖 whereClause 以进行测试和演示。

export const deleteRecords = async (tableName, whereClause) => {
  try {

    // Edit: testing with json string
    const whereClauseString = JSON.stringify('{id: 1000}');
    console.log(whereClauseString); // outputs "{id: 1000}"

    const whereClauseObject = JSON.parse(whereClauseString);
    console.log(whereClauseObject);
    console.log(whereClauseString); // outputs {id: 1000}

    await connection
      .from(tableName)
      .where(whereClauseObject)
      .del()
      .then(count => {
        const successMessage = `SUCCESS: ${count} records deleted from ${tableName}.`;
        console.log(successMessage);
      });
  } catch (err) {
    console.error(err);
  }
};

但是,我收到此错误: “SyntaxError:JSON 中位置 1 的意外标记 i”

编辑:在传入的 json 字符串上使用 JSON.stringify 后,我现在收到以下错误

UnhandledPromiseRejectionWarning: TypeError: 运算符“未定义”是不允许的

由于某种原因,JSON.parse 似乎没有创建 knex 支持的对象

【问题讨论】:

标签: node.js knex.js


【解决方案1】:

字符串'{id: 1000}',不是JSON。 JSON 没有不带引号的键。正确的应该是'{"id": 1000}'

JSON.parse('{id: 1000}');

由于位置 1 中的 i 应该是双引号,因此无法将其解析为 JSON。

Chrome 说 "SyntaxError: Unexpected token i in JSON at position 1" 在这种情况下,Firefox 说 "SyntaxError: JSON.parse: expected property name or '}' at line 1 JSON 数据的第 2 列”

怎么办?

  1. 不要手动构建 JSON。始终使用 JSON.strigify() 或类似名称,并从数据结构中构建它。
  2. 分离您的顾虑。运行查询的函数不应该也是解析 JSON 的函数。这是不必要的限制,因为即使您手头已经有一个对象,您也必须传入 JSON:您需要调用 deleteRecords('table', JSON.stringify(myData)) 以便 deleteRecords() 可以立即再次调用 JSON.parse()deleteRecords() 应该期望一个对象作为输入。将任何 JSON 解析为调用者的任务。
  3. 确保在使用async 时使用await。永远不要只使用一个而没有另一个。

更好:

export const deleteRecords = async (tableName, whereClause) => {
  try {
    const count = await connection.from(tableName).where(whereClauseObject).del();
    const successMessage = `SUCCESS: ${count} records deleted from ${tableName}.`;
    console.log(successMessage);
  } catch (err) {
    console.error(err);
  }
};

【讨论】:

  • 好点。对于第 2 点,这个函数是直接从 graphql api 调用的,所以总是会传入一个字符串。我想我可以有两个单独的函数并让这个函数调用这两个函数,但这仍然结合了两个问题
  • @navig8tr 那么,GraphQL 不应该为您解析 JSON 吗?会不会是你在双重编码?`
  • GraphQL 突变接受两个字符串,tableName 和 whereClause。 whereClause 将如下所示:“{id: 1000}”。
  • @navig8tr 我对 GraphQL 不是很熟悉,但这对我来说有点奇怪。 GraphQL 都是 JSON,为什么它需要一个字符串而不是一个对象?您是否尝试过在whereClause 中使用对象而不是字符串?
  • 请求是 JSON 但参数是作为字符串传入
猜你喜欢
  • 2013-01-06
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2014-08-14
相关资源
最近更新 更多