Search code examples
javascriptjsonparsingjson5

How do I parse this non-standard JSON format?


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.


Solution

  • 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)