I am trying to convert objects defined within a file into arrays.
I am using JSON.parse
on the matched objects.
Some of the multi-line objects are not being replaced.
const txtara = document.querySelector('#demo');
const fixJSON = (invalidJson) => invalidJson
.replace(/(w+)(?=s*:)/g, '"$1"') // Quote keys
.replace(/,}/, '}') // Remove stray commas
.replace(/,ns*}/, '}'); // Remove stray commas (multiline)
const jsonObjectToArray = (jsonObject) => {
const obj = JSON.parse(fixJSON(jsonObject));
return JSON.stringify(Object.values(obj));
}
let content = txtara.value
// Inline object
.replace(/({(.+)})/g, (match, json) => jsonObjectToArray(json))
// Multi-line object
.replace(/({s*n(?:s*w+s*:s*.+,?n)+s*})/, (match, json) => jsonObjectToArray(json));
txtara.value = content;
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
body {
display: flex;
}
#demo {
flex: 1;
resize: none;
color: #EEE;
background: #222;
padding: 0.5rem;
}
<textarea id="demo">
{x:1,y:2}
{x:1,y:2,z:3}
{x:1,y:2,z:3,}
{ x: 1, y: 2, z: 3 }
{
x: 1,
y: 2,
}
{
x: 1,
y: 2
}
{
x: 1,
y: 2,
z: 3
}
{
x: 1,
y: 2,
z: 3,
}
</textarea>
2
Answers
If you need only numbers, then your answer is
You can use
eval()
and a sliding window that you expand whenevereval()
throws an error:But keep in mind
eval
should only be used in trusted environments:See Never use eval()!.