Encountering a problem while parsing JSON in Ruby: Uncaught exception 399 - unexpected token detected!

Whenever I try to use JSON.parse(response['data']), Ruby throws an error:

Uncaught exception: 399: unexpected token at ...

I can't figure out why this is happening. In casperjs, I send the following data back to Ruby:

this.echo('{"data": '+ JSON.stringify(resultFinal) + '}');

To encode the string properly, I used JSON.stringify which gives me the following result:

{"data": "[{'Docket Type': 'MOT - MOTION','Filing Date': '19-AUG-2015', ... 'WAS SOLD TO PNC BANK NATIONAL ASSOCIATION'}]"}

If encoded correctly as a JSON string, Ruby's JSON.parse should be able to parse it without any issues. So, what could be causing the failure?

Answer №1

Analysis of the JSON reveals no issues:

require 'json'

str = <<EOT
{"data": "[{'Docket Type': 'MOT - MOTION','Filing Date': '19-AUG-2015','Filing Party': 'PNC BANK, NATIONAL ASSOCIATION,','Docket Text': 'TO GRANT WRIT OF POSSESSION FOR FAILURE TO VACATE PREMISES F\\B PLT, PNC BANK'},{'Docket Type': 'AFF - AFFIDAVIT','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': 'PURSUANT TO SECTION 83.561, FLORIDA STATUTES F\\B PLT, PNC'},{'Docket Type': '108FF - CAFF/REOPEN ($50.00)','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': '<i>none.</i>'},{'Docket Type': 'RO - REOPEN','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': '<i>none.</i>'},{'Docket Type': 'COS - CERTIFICATE OF SERVICE','Filing Date': '14-JUL-2015','Filing Party': 'NATIONAL CITY BANK,','Docket Text': 'OF ORDER ON OBJECTION TO FORECLOSURE SALE F/B PLT'},{'Docket Type': 'CRT - CERTIFICATE','Filing Date': '01-JUL-2015','Filing Party': '&nbsp;','Docket Text': 'OF DISBURSEMENTS'},{'Docket Type': 'COFT - CERTIFICATE OF TITLE','Filing Date': '01-JUL-2015','Filing Party': '&nbsp;','Docket Text': 'WAS SOLD TO PNC BANK N...
EOT

JSON[str]
# => {"data"=>
#      "[{'Docket Type': 'MOT - MOTION','Filing Date': '19-AUG-2015','Filing Party': 'PNC BANK, NATIONAL ASSOCIATION,','Docket Text': 'TO GRANT WRIT OF POSSESSION FOR FAILURE TO VACATE PREMISES FB PLT, PNC BANK'},{'Docket Type': 'AFF - AFFIDAVIT','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': 'PURSUANT TO SECTION 83.561, FLORIDA STATUTES FB PLT, PNC'},{'Docket Type': '108FF - CAFF/REOPEN ($50.00)','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': '<i>none.</i>'},{'Docket Type': 'RO - REOPEN','Filing Date': '19-AUG-2015','Filing Party': '&nbsp;','Docket Text': '<i>none.</i>'},{'Docket Type': 'COS - CERTIFICATE OF SERVICE','Filing Date': '14-JUL-2015','Filing Party': 'NATIONAL CITY BANK,','Docket Text': 'OF ORDER ON OBJECTION TO FORECLOSURE SALE F/B PLT'},{'Docket Type': 'CRT - CERTIFICATE',...

<p>I'm using Ruby version 2.2.3.</p>

<hr>

<p>The issue arises from transferring a JSON string that has been altered by changing double-quotes to single-quotes. The solution is to revert these changes:</p>

<pre><code>hash = JSON[str]
JSON[hash['data'].tr("'", '"')]
# => [{"Docket Type"=>"MOT - MOTION",
#      "Filing Date"=>"19-AUG-2015",
#      "Filing Party"=>"PNC BANK, NATIONAL ASSOCIATION,",
#      "Docket Text"=>
#       "TO GRANT WRIT OF POSSESSION FOR FAILURE TO VACATE PREMISES FB PLT, PNC BANK"},
#     {"Docket Type"=>"AFF - AFFIDAVIT",
#      "Filing Date"=>"19-AUG-2015",
#      "Filing Party"=>"&nbsp;",
#      "Docket Text"=>
#       "PURSUANT TO SECTION 83.561, FLORIDA STATUTES FB PLT, PNC"},
#     {"Docket Type"=>"108FF - CAFF/REOPEN ($50.00)",
#      "Filing Date"=>"19-AUG-2015",
#      "Filing Party"=>"&nbsp;",
#      "Docket Text"=>"<i>none.</i>"},
#     {"Docket Type"=>"RO - REOPEN",
#      "Filing Date"=>"19-AUG-2015",
#      "Filing Party"=>"&nbsp;",
#      "Docket Text"=>"<i>none.</i>"},
#     {"Docket Type"=>"COS - CERTIFICATE OF SERVICE",
#      "Filing Date"=>...

<p>It's crucial for JSON data to adhere to <a href="http://json.org" rel="nofollow">the specified guidelines</a>. Strings need to be enclosed in double-quotes:</p>

<blockquote>
  <p>A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.</p>
</blockquote>

<p>The practice of encoding JSON within JSON can lead to challenges and potential data corruption. Base64 encoding could be a more reliable approach to ensure data integrity during transfer.</p>

<p>An alternative method involves letting the JSON parser handle the serialization with escaped characters:</p>

<pre><code>require 'json'

foo = JSON[{'a' => 'b'}]
JSON[ {'bar' => foo }] # => "{\"bar\":\"{\\\"a\\\":\\\"b\\\"}\"}"

This process simplifies data retrieval:

JSON[bar] # => {"bar"=>"{\"a\":\"b\"}"}
JSON[bar]['bar'] # => "{\"a\":\"b\"}"
JSON[bar]['bar']['a'] # => "a"

Repeating decoding steps can complicate the process. It's essential to minimize such complexities to maintain data integrity during transmission.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

three.js: shadows created by a mesh with varying levels of transparency

My model has a texture with certain transparent areas (alpha equals zero). But when the model casts a shadow, it looks like it's solid. Is there a way to solve this issue? ...

Error encountered in Express Router middleware (`app.use() function must be provided with a middleware function`)

I've seen plenty of similar questions on this topic, but after reviewing them all, I still haven't found a solution. My current dilemma involves creating an app using Express Router, however I keep encountering the following error: app.use() re ...

Experiencing the "Module not found" issue while incorporating SCSS into React applications

I attempted to apply a SCSS style to my "Logo.js" component, but I am still unable to resolve the error that keeps popping up: ERROR in ./src/components/Logo/Logo.js 5:0-19 Module not found: Error: Can't locate 'logo.scss' in '/Users/a ...

Using pymongo to load a JSON file from mongodump into MongoDB

I have a JSON file that has been converted from mongodump BSON format and I need to insert it into a MongoDB database using pymongo. My current approach involves opening the file, reading its content line by line, converting each line into a JSON object, a ...

Can a single shield protect every part of an Angular application?

I have configured my application in a way where most components are protected, but the main page "/" is still accessible to users. I am looking for a solution that would automatically redirect unauthenticated users to "/login" without having to make every ...

Connect an external pure JavaScript file to my React component

Looking to create a dynamic react component with a festive birthday animation using an external javascript file. I've tried linking the external script like so: componentDidMount() { const script = document.createElement("script"); ...

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Testing Jasmine, Karma, and Angular to create a controller

Can someone help me with identifying where I went wrong? How do I obtain an instance of a controller in Jasmine + Angular? What should I use to resolve this issue? 'use strict'; angular.module('myApp.contact', ['ui.router']) ...

What is the best way to showcase a specific column from a dataset using Vue.js and axios?

Hey there, I'm still getting the hang of all this and haven't quite mastered the jargon yet. Here's what I need help with: I managed to retrieve data from my SQL database using axios, and when I check in (f12) - network - preview, it shows: ...

Adapt the stylesheet for mobile devices using CSS

I am struggling with updating file paths in CSS depending on whether the end user is accessing my site from a PC or mobile device. Below is my CSS code, where I attempted to redirect users if they are on a handheld device: <link rel="stylesheet" type=" ...

"Step-by-step guide on triggering the ng-click function for the first row within an ng

I'm facing an issue where the first set of data from the ng-repeat div is not loading before clicking on the ng-repeat. Below is the code snippet: <div class"profile" ng-repeat="data in information" ng-click="getData(data.i ...

Nextjs doesn't render the default JSX for a boolean state on the server side

I am working on a basic nextjs page to display a Post. Everything is functioning smoothly and nextjs is rendering the entire page server side for optimal SEO performance. However, I have decided to introduce an edit mode using a boolean state: const PostPa ...

The jCapSLide Jquery Plugin is experiencing compatibility issues in Chrome browser

While this JQuery plugin works perfectly in Internet Explorer and Firefox, it seems to be malfunctioning in Chrome. The plugin is not being recognized at all by Chrome, and the captions are appearing below the image instead of on top with a sliding effect. ...

Walls that collide in three.js

I am currently developing a game using three.js and despite being new to this field, I have extensively studied collision documentation. To handle collisions between my boat (inside a cube) and the islands (contained in cubes), I implemented raycasting. He ...

What is the reason behind utilizing arrow functions in React event handlers?

function ButtonIncrement(){ const [count,setCount] = useState(0); render(){ <div> <h3> <button onClick={() => setCount(count+1)}>Increase count for amusement</button> <p>Total C ...

Obtaining information from python script with 'child-process' functions successfully in a regular node.js script, yet encounters issues in a script that is being imported

I'm currently developing a node.js application that involves sending data to a python script for calculations, and then receiving the processed data back in a discord.js command-script command.js, which is executed from the main script index.js. To se ...

Prevent modal from closing when tapping outside of it

I'm currently facing a challenge in creating a popup modal that cannot be closed by clicking outside the modal window. I have explored various solutions involving backdrops but none of them seem to be effective. Any assistance would be greatly appreci ...

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...

The error message "TypeError: string indices must be integers in a complex JSON array" indicates

Currently, I am encountering a TypeError while trying to convert a JSON array into an object list. I have made several attempts to resolve the issue by searching on Google, but I haven't been successful thus far. Would anyone be able to assist me in r ...

I am experiencing a lack of results when attempting to run db.find() in Mongodb

Recently I delved into the realm of MongoDB, deciding to create a basic application that simply showcases data stored in my database. Check out the code snippet below: var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost ...