Troubleshooting a misformatted JSON string that lacks proper double quotes in Java Script

{ DataError: { user_id: [ [Object] ] } }

I want to transform this string into JSON structure like below:

{ "DataError": { "user_id": [ [Object] ] } }

Is there a potential method to achieve this outcome from incorrectly formatted JSON string?

Answer №1

If you can confirm that the incorrectly structured string is secure and only contains poorly formatted JSON (meaning it won't run any additional javascript), one approach would be to use an eval function followed by JSON.stringify method.

JSON.stringify(eval('(' + customString + ')'));

Answer №2

I stumbled upon an amazing javascript library that saved the day for me. https://github.com/freethenation/durable-json-lint

It transformed my messy json string into a well-formed json string!

durableJsonLint = require('durable-json-lint');
console.log(durableJsonLint('{name:"value", \'array\':[call(), 0x11]}'))
// The above code will output the following to the console
{
   "json":'{"name":"value", "array":[null, 17]}',
   "errors":[{
         "column":1,
         "description":"Keys must be double quoted in Json. Did you mean \"name\"?",
         "lineNumber":1,
         "status":"correctable"
      },{
         "column":15,
         "description":"Json strings must use double quotes",
         "lineNumber":1,
         "status":"correctable"
      },{
         "column":24,
         "description":"You can not make function calls in Json. Do you think I am a fool?",
         "lineNumber":1,
         "status":"fail"
      },{
         "column":32,
         "description":"Invalid Json number",
         "lineNumber":1,
         "status":"correctable"
      }
   ]
}

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

Encountering the "test exited without ending" error while using asynchronous forEach loops with tape

My Current Project Edit: I created a repository with a simplified version of the issue I am facing. Currently, my focus is on setting up automated frontend testing using tools like browserstack, selenium-webdriver, and tape. More information about tape ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...

Retrieving objects from Firebase in a loop using promises

Seeking guidance on handling promises in AngularJS as a newcomer. Struggling with merging data from two asynchronous arrays into a single array within a for-loop. Encountering a bug where the same picture is displayed for all entries despite different user ...

Is it possible to implement a wsdl webservice in Phonegap?

Does anyone know the best way to call a wsdl webservice in Phonegap? Any suggestions on source code or tutorials that could be helpful? ...

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

Convert Ruby array into a hash using specific parameters

Here is an array I have: fruits = ["apple", "banana", "orange"] My goal is to convert it into a JSON format like this: '{"apple": {}, "banana": {}, "orange": {} }' I specifically want to avoid this format: '{"apple"=> {}, "banana"=& ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Unit tests are successful, but an error occurs stating "headers cannot be set after they have been sent."

Currently, I am working on writing unit tests for the API endpoints of my very first express app. I am using a data structure as a placeholder for a database and all the tests are passing successfully. However, I encountered an error in the console stating ...

Issue with ESLint: Unexpected token found in JavaScript when converting to a dictionary

I've implemented a JavaScript code snippet that loops through an array of fields to find specific properties and then adds them to a dictionary. For another example, you can check out this site. return this.getFields() .reduce((mappings, field) =& ...

Guidelines for parsing a JSON response and retaining specific attributes

I am currently working on parsing the response from the following link: . My program is expected to receive a response like this: [ { "createdAt": "2015-06-15T13:10:43.000Z", "domain": "000.biz", " ...

Discovering the method to retrieve the information of the selected item in AngularJS

My table is using the ng-repeat in the <tr> element to load content dynamically from a JSON file. Each row has a unique ID in the table. I need a way to access the inner HTML of the respective row's ID column when it is clicked. Is there a solut ...

Prevent scrollbar from appearing while splash page loads

Looking for help with a script to create a splash/intro page loader. $(function(){ setTimeout(function() { $('#splash').fadeOut(500); }, 6000); }); The current script hides the intro page after 6 seconds, ...

Implementing advanced checkbox filtering feature in React

Does anyone have experience with creating dynamic Checkbox filtering in React using Material-UI? I'm finding it challenging because the checkbox options are generated dynamically from incoming data and need to be categorized by type of Select componen ...

Babel Compile disrupts the flow of commands

I'm facing an issue while attempting to launch my development server after Babel successfully compiles my files. However, the command chain seems to halt right after Babel displays the compilation success message. Babel has completed compiling 82 f ...

Upon attempting to fetch input by name, Puppeteer reported the error message: 'Node is not clickable or not an HTMLElement'

This is the structure of my HTML: <div id="divImporte"> <p class="btn01"> <input type="button" name="Enviar Tasas" value="Enviar Tasas"> </p> </div> Here are the diffe ...

What is the best way to convert the declaration of Mybean within "Type type = new TypeToken<List<Mybean>>(){}.getType()" into a parameter?

Here is the code I'm using to convert a jsonString into a collection. public static List<Itembean> getData(String jsonString){ Gson gson = new Gson(); Type type = new TypeToken<List<Itembean>>(){}.getType(); ...

Differences between Typescript Import and JavaScript import

/module/c.js, attempting to export name and age. export const name = 'string1'; export const age = 43; In b.ts, I'm trying to import the variables name and age from this .ts file import { name, age } from "./module/c"; console.log(name, ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Click event to verify, delete, and include class identifier in angular13

Looking to enhance functionality by dynamically adding and removing the 'active' class to 'li a' elements on click. While the current code performs well when clicking from top to bottom, it fails to work in reverse order. component.htm ...