0

I have a string object which is as follows:-

[{"TradeId":123423,"TradeDate":"2017-12-11T18:30:00.000Z","Commodity":"AL","Side":"Buy","Qty":100,"Price":2000,"Location":"NY"},
{"TradeId":123428,"TradeDate":"2017-12-15T18:30:00.000Z","Commodity":"AL","Side":"Buy","Qty":100,"Price":2000,"Location":"NY"}]

I want to use this as an array on which map can be invoked. How can this be achieved.

I did JSON.parse() of this string, but I get an error stating the following:-

Unexpected token o in JSON at position 1

When I do

JSON.parse('[{"TradeId":123423,"TradeDate":"2017-12-11T18:30:00.000Z","Commodity":"AL","Side":"Buy","Qty":100,"Price":2000,"Location":"NY"},
    {"TradeId":123428,"TradeDate":"2017-12-15T18:30:00.000Z","Commodity":"AL","Side":"Buy","Qty":100,"Price":2000,"Location":"NY"}]')

note the quotes ('') , from my node terminal, it works!!!

please note that I get this string from a websocket.

My end goal is to use this string as an Array on which I can use the map operation

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

After it is dispatched above(react+redux), its used is some component as follows:-

trades.map((trade, index) => {...})

Thanks, Amar

9
  • 12
    It's already an object, not a string. Don't use JSON.parse Commented Jan 2, 2018 at 12:04
  • The error indicates that the value is already an object. See for yourself: JSON.parse([{}]). Commented Jan 2, 2018 at 12:05
  • But get this error when I try to do trades,map(...) trades.map is not a function Commented Jan 2, 2018 at 12:07
  • Also 'typeof trades' gives me string as output Commented Jan 2, 2018 at 12:08
  • Show us the exact code. Commented Jan 2, 2018 at 12:09

2 Answers 2

3

JSON.parse assumes that whatever you pass to it is a string.

Your data is already an object. JSON.parse will cast said object to a string, then try to parse it. Basically, something like this:

JSON.parse(obj.toString())

Casting a object to string like that returns "[object Object]"

Now guess where the "Unexpected token o in JSON at position 1" error gets its "o" from?

TL;DR: Don't use JSON.parse. Your data already is an object.

Sign up to request clarification or add additional context in comments.

1 Comment

My String is an array of objects, but I am unable to call the map function on it, typeof says that it is a string
0

I was able to solve this.

The problem was not here, but in the part of the code that was getting the message from rabbitMQ using amqplib.

After getting the message I did a JSON.parse(msg.content) instead of msg.content.toString() and it resolved the issue!! Thanks a lot everyone for their time and effort.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.