Error: JSON Parsing failed due to invalid formatting of the

I am facing a challenge with an object that contains special characters like quote ('), slash (/), or Environmental.NewLine.

I have converted this object into a JSON string and attempted to assign it to a jQGrid. However, it keeps showing an error message stating "Invalid JSON Parser error."

How can I successfully parse this object?

 myObj = new { Text = @"Samp'le value" }

In ASP.Net MVC, return JSON(myObj) is typically used for creating JSON data.

Does anyone know where we should configure the handling of these special characters like ' / Environmental.NewLine(\n) when parsing JSON?

Is there any other library that needs to be utilized for handling these situations, such as Newtosoft JSON?

JSON Data From Server

 {"total":1 ,"page":1,"records":3,"rows":[{"i":0,"cell":"","1","1","DesSinglApostropAndURLhasEnterKeyChar",
"Samp'le value","http://google.com/Dashboard.aspx?ParcelNbr= {SITE_APN}","False","",""]},"i":1,"cell":"","2","2","DesWithSlashAndURLwithSlash",
 "Sample\value2","http://Googole.com/Dashboard.aspx?ParcelNbr={SITE_APN}&ABC=\XYZ","False","",""]},{"i":2,"cell":["","3","3","DesWithAmpersand","Sample & value3"","http://Googole.com","False","",""]}]}

Answer №1

Make sure to escape only the characters `"` and `\` according to the specification (refer to here or here). Other characters may be escaped as needed, while an unescaped `'` character should not be considered an error. There could be another reason for the "Invalid JSON Parser error" that you encounter.

To avoid errors, include a more comprehensive JavaScript code snippet showing how jqGrid is used, along with the ASP.NET MVC controller action code or a complete JSON response from the server. Utilize libraries like Json.NET to ensure well-formatted JSON data.

Ensure to use the `autoencode: true` option in jqGrid to display text data accurately. Additionally, make use of the `datatype: "json"` and `jsonReader` options as per the documentation found here. Simply producing correctly formatted JSON or XML data might not suffice; including jqGrid options that specify the data format precisely could be necessary.

UPDATED: Validate your JSON data using tools like jsonlint.org as the data appears to be corrupted. Pay attention to syntax errors such as:

  • Using `"cell": ""` instead of `"cell": [""]`
  • Misplacement of `}, "i": 1,` rather than `}, {"i": 1,`
  • Inconsistencies like `"Sample\value2"` instead of `"Sample value2"` or `"Sample\\value2"`
  • Errors in formatting URLs like `"http://Googole.com/Dashboard.aspx?ParcelNbr={SITE_APN}&ABC=\XYZ"` which should be corrected to `"http://Googole.com/Dashboard.aspx?ParcelNbr={SITE_APN}&ABC=XYZ"`
  • Improper handling of special characters in values such as `"Sample & value3""` which should be rectified to `"Sample & value3"`

It is also recommended to use `id` property instead of `i` property in the JSON response for jqGrid compatibility. Refer to the jqGrid documentation for guidance on proper data format expectations. A fixed version of the JSON response should resemble the following:

{
    "total": 1,
    "page": 1,
    "records": 3,
    "rows": [
        {
            "id": 0,
            "cell": [
                "",
                "1",
                "1",
                "DesSinglApostropAndURLhasEnterKeyChar",
                "Samp'le value",
                "http://google.com/Dashboard.aspx?ParcelNbr= {SITE_APN}",
                "False",
                "",
                ""
            ]
        },
        {
            "id": 1,
            "cell": [
                "",
                "2",
                "2",
                "DesWithSlashAndURLwithSlash",
                "Sample value2",
                "http://Googole.com/Dashboard.aspx?ParcelNbr={SITE_APN}&ABC=XYZ",
                "False",
                "",
                ""
            ]
        },
        {
            "id": 2,
            "cell": [
                "",
                "3",
                "3",
                "DesWithAmpersand",
                "Sample & value3",
                "http: //Googole.com",
                "False",
                "",
                ""
            ]
        }
    ]
}

Consider reviewing examples of ASP.NET MVC usage with jqGrid and adjust your server-side code accordingly.

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

Creating a cascading select menu based on the selected value of another select menu

I am in the process of creating a menu that displays two lists for regions: one <select> for selecting the region and another <select> for choosing from available municipalities within that region. I have set up a <form> and I utilize Jav ...

The JavaScript file fails to load when accessing port 8080

As I embark on my journey into backend development, please bear with me. Currently, I am working on a JavaScript program that retrieves text data from my localhost. I have set up an HTTP server using Node.js which serves as a regular HTTP server. The serve ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...

Tablib encounters an issue while converting JSON API response into XLSX file, triggering a KeyError:0 error

My goal is to take the JSON response from an API call and convert it into an excel file without needing specific headers or data. I simply want to capture everything that the call returns. After some research, I came across the tablib library. It worked s ...

What is the best approach for managing Create/Edit pages in Next.js - should I fetch the product data in ServerSideProps or directly in the component?

Currently, I am working on a form that allows users to create a product. This form is equipped with react-hook-form to efficiently manage all the inputs. I am considering reusing this form for the Edit page since it shares the same fields, but the data wil ...

Unable to bypass Django ForeignKey field validation despite specifying blank=True and null=True

Working with Django REST Framework, I have a model called MyModel that is related to another model called MyOtherModel in a many-to-one relationship: models.ForeignKey(MyModel, related_name="my_other_models", blank=True, null=True)<br> Even though ...

Upon initialization, my data is not being rendered by componentDidMount, instead, it is only displayed during

As a newcomer to React, I am aware that there may be a more efficient way to accomplish this task. Currently, I am trying to display all events associated with a specific group by passing the group's ID as a prop to the Events component. The Events co ...

Calculating the bounding box of an Object3D with BufferGeometry in Three.js using JavaScript

Having an Object3D with various levels of children (more Object3Ds or Meshes/Lines), I am trying to compute a bounding box of the object and all its descendants similar to the setFromObject() method in the Box3 class. Unfortunately, I can't utilize t ...

Have the functionality of right clicking and selecting Paste work in the input field using style=text and a button

Here is the code I am using: <script type="text/javascript"> $(document).ready(function() { $('#submit').prop('disabled', true); $('#links').change(function() { $('#submit').prop('disabled ...

Exploring the wonders of HTTP requests through pure pipes in Angular 5

I've been working on a pipe that converts currency values from one to another by making an HTTP call. The idea is to pass in the source and destination currencies as parameters. @Pipe({ name: "currencyConverter" }) export class CurrencyConverterP ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

Executing ForceAtlas2 algorithm from a predetermined starting point within Sigma.js

I need assistance with rendering a complex network using the React-Sigma wrapper. The base structure of this network consists of numerous nodes of degree one and some nodes with high degrees. I have prepared my graph data with x and y coordinates that repr ...

Node replication including a drop-down menu

Is there a way to clone a dropdown menu and text box with their values, then append them to the next line when clicking a button? Check out my HTML code snippet: <div class="container"> <div class="mynode"> <span class=& ...

Images within inline blocks appear to be extending beyond their containing div as though they are

When I check my website in various browsers such as Firefox, IE, Edge, and Safari, I noticed that the images in the "My Specialties" section of the left column are extending outside of the div instead of fitting within it. This problem also occurs in Chrom ...

Wordpress Ajax Login Issues - Error Code 302

I am currently working on implementing a basic Ajax Login system using Wordpress. However, I have encountered an issue where my system fails every time the "wp_signon" function is triggered, and the only feedback I receive is as follows: POST myurl/wp-adm ...

Utilizing React Higher Order Components for Implementing Context API Within Lifecycle Functions

Seeking assistance in creating a React HOC to utilize context within a lifecycle method. Encountering the following error... (0, _withContext.withContext) is not a function. (In '(0, _withContext.withContext)(TestScreen)','(0, _withContext ...

It is not possible to make any further changes to the scene in THREE.js

Here is an example you can check out: Example Link I noticed that in newer versions of THREE.js, if the render function is called before adding additional objects to the scene, those objects will not be visible even with multiple subsequent calls to rend ...

Unable to locate the <router-view> component within VueRouter

I recently completed a project using Vue.js 3.2.13 and Vue-Router 4.0.14. Despite my efforts to ensure everything was set up correctly, I encountered an error in the browser that said "[Vue warn]: Failed to resolve component: router-view". The specific lin ...

PHP outputs JSON formatted data in a single long line

Here is the PHP script I wrote. do2:locu alexus$ cat venuesearch.php <?php $KEY='XXXXXXXXXXXXXXX'; $URL='http://api.locu.com/v1_0/venue/search/?api_key='; $ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $URL.$KEY); curl_setopt($ch ...

Is it possible to display events on fullcalendar.io using PHP and MySQL?

I'm currently trying to integrate a calendar feature on my website using PHP's "while" command. I don't have knowledge of JSON or AJAX, so I'm unsure if those are viable options for me. The issue I'm facing is that the current code ...