I have as an input an invalid JSON string with this structure:
{
"Seq_N":66,
"Uptime":728,
"Hum":33,500000,
"Temp (C)":20,129999
}
I have no accesso to the code that produces the invalid JSON string so I can't fix the string before it's generated
In order to make the JSON string valid, I need to replace the comma character inside the Hum and Temp fields with a dot character, but I also need to keep the comma separators of the JSON string (in order not to break the JSON syntax)
Does anyone know a clean function/regex to do this?
Thanks in advance
CodePudding user response:
Negative lookahead would do the job.
const foo = '{ "Seq_N":66, "Uptime":728, "Hum":33,500000, "Temp (C)":20,129999 }';
const cleanedFoo = foo.replace(/,(?![" ])/g, ".");
console.log(JSON.parse(cleanedFoo));
The regex means:
,
match comma,
(?!
only if it's not followed
[" ]
by either double quotes or space. (Yes, this so-called JSON is seriously malformed).
CodePudding user response:
You can use regex like this, but wouldn't it be better to edit the value before creating the json?
var json = `{
"Seq_N":66,
"Uptime":728,
"Hum":33,500000,
"Temp (C)":20,129999
}`;
json = json.replace(/("(Hum|Temp \(C\))":\d ),/g, '$1.');
console.log(json)
CodePudding user response:
If I understand the question correctly, the following code should do the job:
$(".stat-item").each(function () {
var inner_context = $(this).text();
$(this).text(inner_context.replace(/[\.] /g, ","));
});