Unexpected token o in JSON at position 1


I keep getting this error in this block of code below:

function openWebsocket(url) { var ws; ws = $websocket(url); ws.onOpen(function(event) { console.log(' Websocket connection established:', event); }); ws.onMessage(function(message) { var userObj = UserFactory.getUserObject(); var settings = userObj.alert_settings; // The JSON parsing... var parsedMsg = JSON.parse(message.data); var alert = JSON.parse(parsedMsg); var date = new Date(parseFloat(alert.start_epoch+'000')); alert.hour = date.getHours() +':'+date.getMinutes(); alert.percent_change = Math.round(alert.percent_change); var shouldPush = main_alert_filter(settings, alert); updateFeed(alerts, shouldPush, alert); }); }

I've looked at both <a href="https://stackoverflow.com/questions/15617164/parsing-json-giving-unexpected-token-o-error" rel="nofollow">Parsing JSON giving "unexpected token o" error</a> and <a href="https://stackoverflow.com/questions/8081701/i-keep-getting-uncaught-syntaxerror-unexpected-token-o" rel="nofollow">I keep getting "Uncaught SyntaxError: Unexpected token o"</a>

However neither answer helped. Because when I first run JSON.parse(message.data) I get a string back not an Object. So thus I have to run JSON.parse again to finally get a real object back.

<a href="https://i.stack.imgur.com/ef2gJ.png" rel="nofollow"><img alt="enter image description here" class="b-lazy" data-src="https://i.stack.imgur.com/ef2gJ.png" data-original="https://i.stack.imgur.com/ef2gJ.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" /></a>

<strong>This is what message.data looks like:</strong>

" "{\"term\": \"\\\"nike\\\"\", \"percent_change\": 125, \"hour\": \"10:9\", \"term_id\": 2890413, \"start_epoch\": 1420474140, \"term_trend_id\": 793950, \"end_epoch\": 1420477740, \"formatted_date_difference\": \"January 5, 2015\", \"tickers\": [\"NKE\", \"$PUM\", \"ADDYY\", \"LULU\", \"UA\", \"HIBB\"], \"twitter_preview\": \"\", \"type\": \"spike\", \"approved\": 1, \"search_preview\": [\"\"]}" "

<strong>Now after the first parsing parsedMsg is a string that looks like this:</strong>

{"term": "minimum wage +increase", "percent_change": 729, "hour": "9:14", "term_id": 2522115, "start_epoch": 1447168440, "term_trend_id": 657898, "end_epoch": 1447175700, "formatted_date_difference": "November 10, 2015", "tickers": ["$JAB", "$SLCY", "AAL", "AAPL", "ABCD", "ABTL", "ADDYY", "ADM", "AEO", "AFCO", "AHC"......

<strong>Finally I need an actual object, so I have to run JSON.parse again to get this:</strong>

Object {term: "minimum wage +increase", percent_change: 729, hour: "9:14", term_id: 2522115, start_epoch: 1447168440…}

Another thing to note, I never get that error when I'm stepping through in Chrome. It only happens when I don't have the breakpoint set. Could this be a race condition type issue? Like it tries to JSON.parse something that isn't ready to be parsed?

<hr />


Ok so sometimes the JSON is invalid apparently and sometimes not, so far I'm doing good without errors with the following snippet, thoughts?

if (typeof alert === 'object') { // do nothing... } else { var alert = JSON.parse(alert); }

Most of the time the alert result of JSON.parse(message.data) is a string so I need the other check to double parse it.


The JSON string you specified with message.data is not a well formed JSON parsed as String. It might be because the server is sending you a multi-part message during/after establishing the connection.

I suggest you print the message object received in OnMessage function and analyze if they are fully formed valid JSON Strings.


Why would you parse your json second time, its already been parsed in the first attempt.

Have a look at the <strong>snippet</strong>

<pre class="snippet-code-js lang-js prettyprint-override">var obj = "{\"term\": \"minimum wage +increase\", \"percent_change\": 729, \"hour\": \"9:14\", \"term_id\": 2522115, \"start_epoch\": 1447168440, \"term_trend_id\": 657898, \"end_epoch\": 1447175700, \"formatted_date_difference\": \"November 10, 2015\", \"tickers\": [\"$JAB\", \"$SLCY\", \"AAL\", \"AAPL\", \"ABCD\", \"ABTL\", \"ADDYY\"]}"; $(function(){ var data = JSON.parse(obj); alert(typeof data); console.log(data.tickers[0] +" -> an item in `tickers` array"); console.log(data.tickers); }); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


It looks like Your <strong>message.data</strong> is incomplete.

Take a look on the library docs You are using, maybe you should collect the data until it's end? Maybe there is some onEnd method?


  • How do I provide inline input to an IPython (notebook) shell command?
  • How to append distinct records from one table to another
  • Qpython unicode strings
  • Run python script inside powershell script
  • Copying files and creating new folders based on “creationdate”
  • Escape exclamation mark in batch file
  • How to restrict number of concurrent processes?
  • Selenium and Google - How do you use cookies?
  • Catching exception and throwing the same?
  • Use neo4j server instead of embedded mode
  • Connecting bluetooth device to windows phone 8 application
  • Best practice to eliminate magic numbers within a member function
  • CXF JAXB JAXBEncoderDecoder unmarshalling error : unexpected element when having qualified elements
  • Unexpected token ILLEGAL while running node.js mocha test
  • How to remove a SwiftyJSON element?
  • Breaking out column by groups in Pandas
  • How solve “Qt: Untested Windows version 10.0 detected!”
  • Time complexity of a program which involves multiple variables
  • Is my CUDA kernel really runs on device or is being mistekenly executed by host in emulation?
  • Does CUDA 5 support STL or THRUST inside the device code?
  • When should I choose bucket sort over other sorting algorithms?
  • Hazelcast - OperationTimeoutException
  • To display the title for the current loaction in map in iphone
  • Jquery - Jquery Wysiwyg return html as a string
  • Akka Routing: Reply's send to router ends up as dead letters
  • SVN: Merging two branches together
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • AT Commands to Send SMS not working in Windows 8.1
  • Arrays break string types in Julia
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • WPF Applying a trigger on binding failure
  • How do I configure my settings file to work with unit tests?
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Java static initializers and reflection
  • Can Visual Studio XAML designer handle font family names with spaces as a resource?
  • apache spark aggregate function using min value
  • Is it possible to post an object from jquery to bottle.py?
  • Sorting a 2D array using the second column C++