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

如何用JavaScript将字符串解析为二维数组?JSON.parse报错求解

Fixing SyntaxError When Parsing a 2D Array with JSON.parse()

Hey there! Let's break down why you're running into that SyntaxError and how to fix it quickly—this is a super common gotcha with JSON parsing, so we'll get your 2D array working in no time.

Common Causes & Fixes

  • Incorrect quote usage
    JSON strictly requires double quotes (") for strings and property names. If your input uses single quotes ('), that's a no-go.
    ❌ Wrong: [['red', 'blue'], ['green', 'yellow']]
    ✅ Correct: [["red", "blue"], ["green", "yellow"]]

  • Trailing commas
    Extra commas at the end of arrays (or objects) will break JSON parsing. Even if JavaScript allows it, JSON doesn't.
    ❌ Wrong: [[1, 2], [3, 4],]
    ✅ Correct: [[1, 2], [3, 4]]

  • Unescaped special characters
    If your string elements contain double quotes, backslashes, or other special characters, you need to escape them with a backslash (\).
    ❌ Wrong: [["He said "hello""], ["Path: C:\folder"]]
    ✅ Correct: [["He said \"hello\""], ["Path: C:\\folder"]]

  • You're not actually passing a string
    Double-check that your input is a string, not already an array. If you run JSON.parse() on an existing array, you'll get a SyntaxError. Use console.log(typeof yourInput) to confirm—if it returns object, you don't need to parse it at all!

Working Example

Here's a quick snippet to demonstrate the correct approach:

// Valid JSON string representing a 2D array
const valid2DArrayString = '[["apple", "banana"], ["orange", "grape"], [1, 2, 3]]';

try {
  const parsedArray = JSON.parse(valid2DArrayString);
  console.log("Parsed 2D array:", parsedArray);
} catch (error) {
  console.error("Parsing failed:", error.message);
}

If you're still stuck, try testing small chunks of your string in the browser console with JSON.parse()—the error message will usually point to the exact character where the problem occurs (like "Unexpected token , in JSON at position X"). That makes it easy to track down the issue.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:42:51