How do I parse this non-standard JSON format?

825 Views Asked by At

I want to know some process information ran on the VPS with PM2. But, with the JSON string return by PM2, we can't run JSON.parse() because the JSON is broken.

An example of what PM2 returns:

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

But, if you know how the JSON.parse work, you know the problem. We can't parse this string.

Do you have idea to resolve this problem with another function ?

Thanks in advance.

3

There are 3 best solutions below

2
On BEST ANSWER

Here is a solution for your specific non-json format. The trick is to make sure to have double quotes around keys...

function customParse(string){
  return JSON.parse(string
                    .replace(/\s|"/g, '')        // Removes all spaces and double quotes
                    .replace(/(\w+)/g, '"$1"') // Adds double quotes everywhere
                    .replace(/"(\d+)"/g, '$1')   // Removes double quotes around integers
                   )
}

// Testing the function
let PM2_string = '{data: 0, informations: "hello", name: "test"}'
let PM2_obj = customParse(PM2_string)

// Result
console.log(PM2_obj)
console.log(PM2_obj.data)
console.log(PM2_obj.informations)
console.log(PM2_obj.name)

0
On

It seems like your string is encoded in regular JavaScript or JSON5. JSON5 is a library which allows JSON to be defined in a similar way you would use it in regular JavaScript (without unnecessary ", etc.). Install the library and parse the string with JSON5.parse(). Reference: https://json5.org/

0
On

the string is in JSON5 format and not regular JSON format. To parse a JSON5 string in JavaScript, you will need to use a library that supports the JSON5 format, like json5.

install:

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

By the way, you could also use Hjson to parse that string. JSON5 is a more widely adopted format than Hjson, and has been around for longer. Hjson, while still relatively popular, can be a good choice for configuration files where human readability and ease of use are a priority.