Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way that can programmatically fix JSON syntax error in javascript?

My function receives a JSON string that may have syntax error, how can I fix the error in my function so that I can call JSON.parse()?

Question story: I want to parse the command output of sudo lshw -class network -json which is a linux command. For example, the PC has 2 NICs, so the command output has 2 JSON objects. An exmpale is as following:

{
    "businfo" : "pci@0000:01:00.0",
    some other keys
}
{
    "businfo" : "usb@1:4",
    some other keys
}

NOTE: the 2 objects has no "," seperator. So JSON.parse() will generate error.

ODD: another hyper-v vm's lshw has the same version as used above, but it can generate correct JSON with "," between 2 objects. Same command line.

like image 673
McArthor Lee Avatar asked Dec 07 '25 04:12

McArthor Lee


1 Answers

IF the only problem is that there is no comma between the objects and the format of the string is the same you can do string replace for '} {' to '}, {', and then the resulting string should be parseable. Hope that would help.

like image 72
Alexandr Mihalciuc Avatar answered Dec 08 '25 19:12

Alexandr Mihalciuc