What is the best way to handle this unconventional JSON structure?

Looking for some insight on retrieving process information from a VPS with PM2. However, the JSON string returned by PM2 is malformed, making it impossible to run JSON.parse().

An example of the output provided by PM2:

'{data: 0, informations: "hello", name: "test"}'

If you are familiar with how JSON parsing works, you'll understand the issue at hand - this string cannot be parsed.

Do you have any suggestions for resolving this issue using an alternative function?

Thank you in advance.

Answer №1

It appears that the data you are working with is encoded using either regular JavaScript or JSON5 format. JSON5 provides a flexible way to define JSON objects in a structure similar to standard JavaScript, allowing for easier readability and manipulation. To handle this data, consider installing the JSON5 library and use JSON5.parse() method for parsing. For more information about JSON5, please visit:

Answer №2

Looking for a solution to handle non-json formats? Here's a clever trick - ensure that keys are enclosed in double quotes...

function convertNonJson(string){
  return JSON.parse(string
                    .replace(/\s|"/g, '')        // Eliminate spaces and double quotes
                    .replace(/(\w+)/g, '"$1"') // Introduce double quotes everywhere
                    .replace(/"(\d+)"/g, '$1')   // Remove double quotes around integers
                   )
}

// Test the function
let inputString = '{data: 0, information: "hello", name: "example"}'
let outputObject = customParse(inputString)

// Output
console.log(outputObject)
console.log(outputObject.data)
console.log(outputObject.information)
console.log(outputObject.name)

Answer №3

If you're dealing with a string in JSON5 format instead of regular JSON format, parsing it in JavaScript requires using a library that supports JSON5 like json5.

To get started, follow these steps:

npm install json5
import json5 from 'json5';
const str = "{data: 0, informations: 'hello', name: 'test'}";
const obj = json5.parse(str);

Alternatively, consider utilizing Hjson for parsing the string. While JSON5 is more commonly used and established than Hjson, the latter can be beneficial for configuration files that prioritize human readability and ease of use.

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

Utilizing chrome.scripting to inject scripts in TypeScript

I am currently facing an issue wherein I am attempting to integrate chrome extension JavaScript code with TypeScript: const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); let result; try { [{ result }] = await c ...

JS: Initiating a new keypress operation

When I press the Tab key, I want it to do something different instead of its default action. Specifically, I have a text box selected and I would like it to add spaces (essentially making the textarea behave like a text editor). How can I trigger this type ...

"Utilizing jQuery Autocomplete with an external data source and interactive row additions

I have come up with a plan: When the user types in the search textbox, it will show autocomplete suggestions and display the result on textbox 1, textbox 2, textbox 3. The user can then enter the desired Quantity in textbox 4. After finding an item and ...

Decoding an array in JSON format from PHP

Hey there! Currently, I am working with an associative array in my PHP file, which I convert into a JSON object and pass to my JavaScript file. My goal is to loop through this array and identify the item with a matching key. Here's what I have done so ...

What is Angular's approach to managing the @ symbol in view paths?

I found some interesting data lake sources on AWS. I came across their package.js file, which includes the following code: '@package': { templateUrl: 'package/package.html', controller: 'PackageCtrl' } I am curious a ...

Leverage the power of jQuery to display JSON data retrieved from a PHP

I am having trouble with my jQuery AJAX call on a PHP page that outputs JSON. Despite my code seeming correct, the alert() dialog isn't showing and the JavaScript console isn't providing any errors. Can you help me identify what is causing this i ...

Resetting the CSS for an input field: a step-by-step guide

My situation involves having a global CSS style set for text type inputs, such as: input[type=text] { padding:10px; width:100px; //and many more } Now, I am incorporating a plugin called colorpicker into a specific div. This plugin generates some input e ...

Enabling onClick based on conditions

I'm struggling to disable a Link onClick when a certain condition is not met. Attempted to move the logic outside of render using a function, but the button always ends up disabled. Tried CSS to disable click, only to realize that tab and enter can ...

Having issues with Angular http.post not sending data when using subscribe

I'm currently facing an issue with sending data to my API using post.subscribe. Despite the fact that no errors are being thrown, the data is not being sent successfully. It's important to note that the API itself is functioning perfectly. Belo ...

Passing parameters to an external function in order to display a message is proving difficult. An error of type TypeError is being encountered, specifying that the Class constructor AlertMessage cannot be called without using the

Every time I attempt to pass a message as an argument to the showAlert() function, an error is triggered: Error: An instance of the AlertMessage class cannot be created without using 'new' image: I am simply trying to send the message as a para ...

Spring MVC: Issue with POST request and JSON object containing an array resulting in a bad request

Trying to fetch parameters from an http POST request using Spring MVC. The POST request contains the following JSON object (content-type : application/json) with an array of customObjects: { "globalId":"338", "lines":[ { "id": ...

Tips on navigating to a URL with a component in React without losing the passed props

When the onClick event is triggered, I aim to redirect to a new component with props passed to it along with a new URL. My App.js import React from "react"; import Main from "./Components/Main/Main"; import "bootstrap/dist/css/boo ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

jQuery fails to recognize response

Can anyone figure out why my alert isn't functioning correctly? <script type="text/javascript"> function SubmitForm(method) { var login = document.form.login.value; var password = document.form.password.value; ...

Deleting an item using jQuery

In the Document Object Model (DOM), there is a button available to remove the parent element here: <i class="fa fa-times remove-product-compare" aria-hidden="true"></i> Here is an example of my DOM structure: <div class="col-lg-12 col-md- ...

Converting RowDataPacket to an array in Node.js and MySQL API, learn how to convert a RowDataPacket from the MySQL API into an array

Hello, I need assistance with converting my row data packet into an array of arrays or nested arrays. Please provide code snippet below: router.get('/getPosts/:user_id', (req, res, next) => { connection.query('SELECT * FROM files WHERE ...

Deciding whether an altered image has been successfully loaded

Currently, I am stuck on a minor point while creating a small gallery using jQuery. The code snippet looks like this: <script type="text/javascript> $(document).ready(function(){ $('#thumb1').click(function(){ $('#fullimage ...

As the user types, automatically format the input field for a seamless and intuitive experience

My current application is running on Angular 1.3.10 I have implemented a jQuery function to automatically add a backslash to the expiration input field once the user types the third number. Although it was a quick fix, I now aim to move this functionality ...

Store the active tab in AngularJS with Bootstrap to easily remember and display

After creating a basic AngularJS application with the Bootstrap directive, I noticed that some of my pages have tabs. The issue arises when I am on a tab other than the first one and click a link to navigate to another view. Upon returning (using either th ...

What is the best way to convert the data stored in an object to an array?

I have a function that is constantly checking for temperature data: {"a":"43", "b":"43", "c":"42", "d":"43", "e":"40", "f":"41", "g":"100", "h":"42.6"} My goal is to graph this data over time, but I'm struggling with how to structure it to fit the f ...