I need help converting a string value into JSON format:
hello|world|this|is|javascript || my|name|is|mahdi
My current code successfully splits the string using ||
, but I am unable to group the split values into separate arrays in the JSON output. Here is the current result of my code:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
},
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
}
However, I would like the output to have separate arrays for the split values like this:
{
"FILEDS": [
{
"template_id": "123",
"fields_id": "456"
},
[
{
"item": "hello"
},
{
"item": "world"
},
{
"item": "this"
},
{
"item": "is"
},
{
"item": "javascript "
}
],
[
{
"item": " my"
},
{
"item": "name"
},
{
"item": "is"
},
{
"item": "mahdi"
}
]
]
}
Here is a snippet of my code where I split the data and create the JSON array:
<script type="text/javascript" language="JavaScript">
var data = "hello|world|this|is|javascript || my|name|is|mahdi";
var templates = {
FILEDS: []
};
templates.FILEDS.push({
"template_id": "123",
"fields_id": "456",
});
var split_data = data.split("||");
for (var i = 0; i < split_data.length; i++) {
var fields = split_data[i].split("|");
for (var j = 0; j < fields.length; j++) {
templates.FILEDS.push({
"item": fields[j],
});
}
}
console.log(JSON.stringify(templates));
</script>