4

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

another question: there are unexpectable number of spaces between "}" and "{", how to add the ","... I think the problem may be narrowed to: how to use regular expression to replace "}any number of spaces and \n{" with "},{".
Here is the very simple method to do it var str = "{object one} {object two} {object three}"; var res = str.replace(/}\s*{/g,'},{');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.