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

WebSocket获取的JSON字符串转可map数组遇解析错误求助

Fixing "Unexpected token o in JSON at position 1" in React+Redux WebSocket Setup

Hey there, let's break down what's going on here and fix that parsing error once and for all!

Why You're Seeing This Error

That "Unexpected token o" error is a super common gotcha—it almost always means you're trying to parse something that's already a JavaScript object, not a JSON string. Here's the play-by-play:

  • When you call JSON.parse() on an object instead of a string, JavaScript automatically converts that object to the string "[object Object]" first.
  • Trying to parse that string fails immediately because it's not valid JSON (the second character is o, hence the error at position 1).

The reason it worked in your Node terminal is because you manually wrapped the content in single quotes, treating it as a raw string. But in your WebSocket setup, chances are your socket library (like Socket.io) is already automatically parsing JSON messages into JS objects for you—so you don't need to run JSON.parse() at all!

Step-by-Step Fix for Your Code

First, let's confirm what type of data you're actually receiving. Update your socket listener to log the data type:

socket.on('getdata', (msg) => {
  console.log("getdata", msg, typeof msg); // Check if this logs "object" or "string"
  // ... rest of your code
})

Case 1: msg is already an object (most likely scenario)

If the typeof msg logs object, you can skip parsing entirely and pass the data directly to your Redux action:

socket.on('getdata', (msg) => {
  console.log("getdata", msg);
  myStore.dispatch(TradesActions.loadTrades(msg)) // No JSON.parse needed!
})

Case 2: msg is a string (rare, but possible)

If it's actually a string and you still need to parse it, add a safety check to avoid parsing objects by mistake:

socket.on('getdata', (msg) => {
  let tradesData;
  try {
    if (typeof msg === 'object') {
      tradesData = msg;
    } else {
      // Only parse if it's a string
      tradesData = JSON.parse(msg.toString());
    }
    myStore.dispatch(TradesActions.loadTrades(tradesData));
  } catch (err) {
    console.error('Failed to process trades data:', err, msg);
  }
})

Extra Safety for Your Component

To avoid errors when using trades.map() in your component, always verify that trades is an array first:

{Array.isArray(trades) ? (
  trades.map((trade, index) => (
    // Your trade component markup here, e.g.:
    <div key={trade.TradeId}>
      <p>Commodity: {trade.Commodity}</p>
      <p>Price: {trade.Price}</p>
    </div>
  ))
) : (
  <div>No trades available</div>
)}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:53:45