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

如何用JavaScript在后端JSON DB过滤数据并修复解析错误

问题描述

我的后端JSON数据库运行在http://localhost:3000/user,需要用JavaScript实现以下逻辑:

  • 发送HTTP GET请求到后端,过滤出name值为空字符串的用户
  • 若存在此类用户,发送PATCH请求用用户输入的字符串更新数据库
  • 若不存在,弹出提示

当前代码测试时出现错误:Uncaught SyntaxError: "[object Object]" is not valid JSON at JSON.parse。另外我用bash+jq实现过滤的代码如下:

url="http://localhost:3000/user"
response=$(curl -X GET -H "Content-Type:application/json" $url)
responseTest=$(echo $response | jq '.[] | select(.name=="")')
echo $responseTest

错误原因及修复方案

错误根源

这个报错是因为你在调用JSON.parse()时传入了已经解析完成的JavaScript对象,而非原始JSON字符串。比如使用fetch API时,若已经调用过response.json()(该方法会自动把JSON字符串解析为JS对象),再对这个对象执行JSON.parse()就会触发该错误。

修复步骤

1. 正确处理GET请求与数据过滤

用fetch获取数据时,直接通过response.json()解析为JS对象,无需手动调用JSON.parse():

async function getEmptyNameUsers() {
  const res = await fetch('http://localhost:3000/user');
  const users = await res.json(); // 自动解析为JS对象数组
  // 过滤name为空的用户
  return users.filter(user => user.name === '');
}

2. 实现PATCH更新逻辑

获取到目标用户后,遍历发送PATCH请求(假设用户数据包含id作为唯一标识):

async function updateEmptyNameUsers(newName) {
  const targetUsers = await getEmptyNameUsers();
  
  if (targetUsers.length === 0) {
    alert('没有name为空的用户');
    return;
  }

  // 逐个更新符合条件的用户
  for (const user of targetUsers) {
    await fetch(`http://localhost:3000/user/${user.id}`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ name: newName }) // 这里需要把JS对象转为JSON字符串
    });
  }
  alert('更新完成');
}

3. 结合用户输入调用函数

假设页面有输入框和触发按钮,绑定事件实现交互:

// 页面元素示例:<input id="newName" type="text"> <button id="updateBtn">更新空name用户</button>
document.getElementById('updateBtn').addEventListener('click', () => {
  const inputName = document.getElementById('newName').value.trim();
  if (!inputName) {
    alert('请输入要更新的name值');
    return;
  }
  updateEmptyNameUsers(inputName);
});

关键注意事项

  • 避免重复解析:response.json()已经完成JSON到JS对象的转换,直接使用返回值即可
  • PATCH请求的body必须用JSON.stringify()转为JSON字符串,这是和GET请求解析相反的操作
  • 确保后端支持PATCH方法(比如使用json-server时,默认支持该方法)

内容的提问来源于stack exchange,提问作者someguyhello

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:25:02