Unexpected token encountered when using JSON.parse()

I'm encountering an issue where trying to use JSON.parse() on a specific string is resulting in an unexpected token error. It seems to be having trouble with the 'maker' part of the data. Any insight on this issue would be greatly appreciated.

var x = '[{
"db":"COLLECTIONS",
"sisn":"1093041",
"accession":"2011.285.01",
"bowner":"Osgoode Township Historical Society and Museum",
"title":"Wooden pattern for  foundry",
"titlelink":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y",
"maker":[],
"image":"[M3IMAGE]201128501.jpg",
"bookmarked":0,
"refd":0
}]';

var result = JSON.parse(x);

Answer №1

The information provided is processing correctly:

var data = '[{' +
'"db":"COLLECTIONS"' +
',"sisn":"1093041"' +
',"accession":"2011.285.01"' +
',"bowner":"Osgoode Township Historical Society and Museum"' +
',"title":"Wooden pattern for  foundry"' +
',"titlelink":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y"' +
',"maker":[]' +
',"image":"[M3IMAGE]201128501.jpg"' +
',"bookmarked":0' +
',"refd":0' +
'}]';

console.log(JSON.parse(data));

Therefore, the problem may be that (particularly in your scenario) you are encountering a syntax error when attempting to assign a multi-line string. It is not possible to assign multi-line strings in that manner. Here are some alternative solutions:

// combine each line
var data = '[{' +
  '"db":"COLLECTIONS",' +
  '"sisn":"1093041"' +
'}]';
console.log(JSON.parse(data));

// escape each line
var data = '[{ \
  "db":"COLLECTIONS", \
  "sisn":"1093041" \
}]';
console.log(JSON.parse(data));

// use template literals (may not be supported in all browsers!)
var data = `[{
  "db":"COLLECTIONS",
  "sisn":"1093041"
}]`;
console.log(JSON.parse(data));

When utilizing the "combine" method, ensure to escape any single quotes within the string (e.g. this is Marcelino\'s answer).

If applying the "escape" method, be aware that the string should not contain a backslash as it may not be handled correctly by JSON.parse (any clarification on this would be appreciated).

When using the "template literal" method, verify that the browsers you intend to support have this feature or consider using a transpiler such as Babel.

I trust this information is beneficial!

Answer №2

To instruct the JavaScript engine that a string continues on the next line, simply add a backslash at the end of each line. Give this a try:

var x = '[{ \
"db":"COLLECTIONS" \
,"sisn":"1093041" \
,"accession":"2011.285.01" \
,"bowner":"Osgoode Township Historical Society and Museum" \
,"title":"Wooden pattern for  foundry" \
,"titlelink":"http://felix.minisisinc.com/ottawa/scripts/mwimain.dll/475/2/1/109    3041?RECORD&UNION=Y" \
,"maker":[] \
,"image":"[M3IMAGE]201128501.jpg" \
,"bookmarked":0 \
,"refd":0 \
}]';

console.log(JSON.parse(x));

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

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

Calculate the combined sum of values within dynamic inputs that share a common class, and automatically update the sum whenever input values are altered or new rows are added or removed dynamically

$("#add-btn").click(function() { $("#dynamic").append('<tr>' + '<td class="td">' + '<input type="number" name="Debit" class="form-control Debit"/>' + '</td>' + '<td c ...

Two distinct iterations of the identical jquery version sourced from external sources

NOTE: This situation involves having two copies of jQuery with the same version number but different libraries loaded by external sources. This is distinct from the issue of using multiple versions of jQuery on a single page, as discussed here: Can I use m ...

Tips for ensuring that your modal functions properly with an image tag within a figure tag

I'm facing an issue with getting a modal to display on my image gallery. The problem arises when the images are enclosed within figure tags, necessary for my hover effect, causing the modal to malfunction. I suspect that the problem lies within the f ...

"Permission denied to access restricted URI" error encountered while attempting to utilize ng-template functionality

I am attempting to implement ng-include for recursive templates in my HTML. After testing it on jsfiddle and confirming that it works, I tried the same locally. However, I encountered the following error: Error: Access to restricted URI denied createHttpB ...

What is the best way to display or conceal an array object using a toggle switch?

I'm trying to implement a show/hide functionality for descriptions when toggling the switch. Additionally, I want the switch to be initially checked and only show the description of each respective result. However, my current code is displaying all de ...

Is it possible to activate the jQuery .click() function for a button with specific text?

Here's a dilemma I'm facing: $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s ...

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

Tips for preserving login status even after the browser is shut down with the help of JavaScript

I need help with maintaining a user session in my chat application even when the browser is closed. After users log in for the first time, I want their credentials to be remembered by the browser (I'm currently using local storage). How can I ensure ...

Creating a 3D trajectory around the Earth using a Two-Line Element Set (TLE)

I am currently working on a project to develop a 3D scene in JS/React that will visualize the orbit of the ISS around Earth. I have forked a repository from https://github.com/dsuarezv/satellite-tracker. However, I have observed that the current implement ...

Using D3 to create SVG elements in Next.js, the mouseenter event only triggers once

I'm currently developing a React Component that utilizes D3, however, I am facing an issue where the SVG circles are only triggered once. import React, { useEffect, useRef, useState } from 'react'; import * as d3 from 'd3'; import ...

Populate a JSON table in React with checkboxes and automatically mark them based on the JSON data

I'm currently working on creating a React table using JSON data like this: [ { "Id_side": 123, "Name_side": "R4", "Name_cycle": "C1" }, { "Id_side": 345, "Name_side": "M1", "Name_cycle": "C2" ...

When is the best time to assign properties to mobx domain objects?

When it comes to tackling a specific problem in my react/mobx application, I'm facing challenges finding an optimal solution. Imagine having multiple boxes that need to be positioned on the screen based on various factors such as interdependency betwe ...

What are the steps to successfully install OpenCV (javascript edition) on Internet Explorer 11?

I'm currently experiencing issues with getting the OpenCV javascript version to function properly on IE11 for contour detection. While my code runs smoothly on all other up-to-date browsers, I am encountering errors such as: TypeError: Object doesn&a ...

Close button for colorbox modal window containing an iframe

I'm currently utilizing colorbox for a modal popup, and the content of the popup is being sourced from a URL. Since it's displayed within an iFrame, I'm wondering how I can incorporate a close button to the modal popup. Thank you The follo ...

Highcharts plots only appear once the browser window is adjusted

Having some issues while testing out the Highcharts javascript charting library on a specific page. The problem I'm encountering is that none of the data appears until I adjust the browser's size slightly. Prior to resizing, the tooltip does dis ...

If the input is unmounted in react-hook-form, the values from the first form may disappear

My form is divided into two parts: the first part collects firstName, lastName, and profilePhoto, while the second part collects email, password, confirmPassword, etc. However, when the user fills out the first part of the form and clicks "next", the val ...

Creating multiple routes within a single component in Angular without triggering unnecessary redraws

Within the ChildComponent, there is a reactive form that allows for data entry. Upon saving the filled form, the route should be updated by appending an id to the current route. Currently, when saving, the component renders twice and causes screen flicke ...

Send user a notification upon detecting changes in the database - using JavaScript and AJAX!

Hey there! I'm diving into the world of JavaScript and AJAX for the first time, and I could really use some guidance on a particular issue. I'm looking to implement a feature where the user is notified whenever there is a change in a value of a ...

How to insert an image into a placeholder in an .hbs Ember template file

I'm looking to enhance a .hbs template file in ember by incorporating an image. I am not a developer, but I'm attempting to customize the basic todo list app. <section class='todoapp'> <header id='header'> & ...