You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含postId的JSON对象数组转换为纯数值数组并用于SQL查询?

JSON对象数组转纯数值数组的实现方法

需求说明

现有如下格式的JSON对象数组:

[
  { "postId": 17 },
  { "postId": 13 },
  { "postId": 14 },
  { "postId": 10 },
  { "postId": 7 },
  { "postId": 1 },
  { "postId": 2 }
]

需要转换为纯数值数组:

[17, 13, 14, 10, 7, 1, 2]

用于SQL查询(注意:原SQL写法有误,正确写法需使用IN关键字):

SELECT * FROM posts WHERE post_id IN (17, 13, 14, 10, 7, 1, 2);

多语言实现方案

1. JavaScript

使用map方法遍历数组,提取每个对象的postId属性:

const jsonArray = [
  { postId: 17 },
  { postId: 13 },
  { postId: 14 },
  { postId: 10 },
  { postId: 7 },
  { postId: 1 },
  { postId: 2 }
];

const numberArray = jsonArray.map(item => item.postId);
console.log(numberArray); // 输出: [17, 13, 14, 10, 7, 1, 2]

2. Python

通过列表推导式快速提取目标值:

json_array = [
    {"postId": 17},
    {"postId": 13},
    {"postId": 14},
    {"postId": 10},
    {"postId": 7},
    {"postId": 1},
    {"postId": 2}
]

number_array = [item["postId"] for item in json_array]
print(number_array) # 输出: [17, 13, 14, 10, 7, 1, 2]

3. PHP

利用array_column函数直接提取指定键对应的所有值:

$jsonArray = [
    ["postId" => 17],
    ["postId" => 13],
    ["postId" => 14],
    ["postId" => 10],
    ["postId" => 7],
    ["postId" => 1],
    ["postId" => 2]
];

$numberArray = array_column($jsonArray, 'postId');
print_r($numberArray); // 输出: Array ( [0] => 17 [1] => 13 [2] => 14 [3] => 10 [4] => 7 [5] => 1 [6] => 2 )

重要提示

你提供的SQL语句存在语法错误:当需要匹配多个字段值时,不能直接用逗号分隔,必须使用IN关键字包裹数值列表,否则数据库会无法识别该语句。

内容的提问来源于stack exchange,提问作者Omar Dak Elbab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:30:57