Encountering difficulty in parsing valid JSON data from a textarea element using JSON.parse method

This helpful question, this informative one, and others I found were not useful.

The JSON provided below is valid.

However, an error is thrown when trying to parse it using JSON.parse.

Is there a way to successfully parse valid JSON from a textarea element?

Check out the JSfiddle for more details: JSFiddle Link

Answer №1

jQuery uses a non-breaking space nbsp or charcode \xA0 instead of a normal space, so you will need to replace it.

let text = $('#testBox').val();
let jsonObject;
try {
  jsonObject = JSON.parse(text);
} catch (ex) {
  console.log("error: ", ex.message)
}
text = text.replace(/\xA0/g, " "); // or \s but will also replace newline
jsonObject = JSON.parse(text);
console.log("what the name: ", jsonObject.name)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="testBox">
  {
  "name": "Foobar",
  "favorite_pets": ["capybara", "lizard"],
  "favorite_fruits": ["avocado"],
  "address": {
   "city": "FairyVille",
   "street": "42 Main St."
  }
}

</textarea>

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

Ways to incorporate AngularJS variable within a JavaScript function

My current task involves iterating through a JSON file using AngularJS. Below is the function that I am working with: <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> <script> functi ...

Dynamically obtaining the content of a tag using jQuery

Although this question may have been asked multiple times before, I am encountering a peculiar issue. Let me explain the scenario: Within this tag, there is a dynamically loaded integer: <i id="my_id">{{integer value}}</i> I am attempting t ...

Is it advisable to nest constructors and prototypes in JavaScript programming?

Currently, a project I'm working on requires an object type called Chain that generates another object type called Link which is exclusively used by the former. In my past projects, I had embedded the constructor and prototype of Link within the const ...

Stop the reoccurring action for a jQuery plugin by using the clearInterval function

Having a difficulty with clearing the interval inside a jQuery plugin. Below is a simplified code snippet. When attempting to run the following in the Firefox console: $('.banner').pluginName().stop() the console keeps logging `console.log(1)`. ...

Conceal tab content by clicking outside of the tab or its contents

Here is an example of how Elementor tab works. When you click on a tab, the content section appears. I want to be able to close the content section by clicking on any other part of the page, except for the tabs and tab content themselves. This should not a ...

Executing a Visual Basic subroutine from a jQuery dialog box

Currently, I have a form that includes a jQuery dialog creation. Within this dialog, there is a button generated from an ASP server control that should trigger a function in the code behind when clicked. However, I am encountering an issue where the functi ...

Guide on making an API call using the map function

Hey there! I'm currently trying to make an API call within a map function, but it keeps returning as an object.promise. Is there a way to call the API within it without getting this object.promise result? const MatchHistory = ({ history }) => { ...

Find the hex code corresponding to the darkest color in the JSON response

I'm working with a json response that contains various vehicle objects, each with a hexcode value representing the color of the vehicle: [ { "name":"Ford", "hexCode": "4B1A1F"}, { "name":"BMW", "hexCode": "FFFFFF"}, { "name":"Fiat", "hexCode" ...

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

The hide() and on() methods are not compatible with Internet Explorer (IE)

My code is working fine on Google Chrome, but for some reason it's not functioning properly on Internet Explorer (IE). I'm using IE11 and really need this to work on all browsers. Please help me figure out what's going wrong here. $(' ...

Program designed to eliminate any c-style comments found within a JSON file

Imagine having a json file with c style comments /* ... */ added for readability purposes, like this: { "filename" : "alice " , /* name of the file */ /** assume this case never happens "filename" : "alice /*bob*/" **/ /*** some comments */ ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

The progress bar fails to update once it hits 100%

My circle progress bar is not resetting to start over when it reaches 100%. The code seems to work fine in my browser, but for some reason it's not working on JSFiddle. Here is the link: https://jsfiddle.net/BrsJsk/5e9hs69y/5/ window.onload = fu ...

Having trouble properly refreshing Bootstrap scrollspy that is spying on the <body> element

I've been looking at a post on Bootstrap's scrollspy component (found here). In my code, I initialize a new scrollspy to track the body element using: $("body").scrollspy({ offset: 25 }); As my code progresses, I make AJAX requests that add or ...

Adding an array to a JSON array

I am trying to insert additional data into a JSON structure. Here is the current structure: [ { "name": "Sam", "ride": "My Ride test", "session": "6htbgumjtmnxko6r", "info": null }, ] The variables I have are as fo ...

What is the best method to find a matching property in one array from another?

I am working with two arrays in TypeScript. The first one is a products array containing objects with product names and IDs, like this: const products = [ { product: 'prod_aaa', name: 'Starter' }, { product: 'prod_bbb&apos ...

If the socket cannot be found, an error callback will be activated

Below is the method I am using to send a message to a targeted socket connection. socket.broadcast.to(socketid).emit('message', JSON.stringify(data)); If the specified "socketid" does not exist, is there a mechanism in place to capture the erro ...

Utilizing Google chart tools allows you to incorporate multiple charts onto a single page

<html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"> </script> <script type="text/javascript> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoa ...

NVDA fails to announce the "dialog" when a Modal is launched

When testing this simple modal example, I noticed that although the role is set to dialog and focus is correctly received on the dialog container when it opens, NVDA fails to announce the word 'dialog' at the beginning. This issue has been report ...

In a Custom Next.js App component, React props do not cascade down

I recently developed a custom next.js App component as a class with the purpose of overriding the componentDidMount function to initialize Google Analytics. class MyApp extends App { async componentDidMount(): Promise<void> { await initia ...