如何在 JavaScript 中将文本转换为 JSON
How to convert text to JSON in JavaScript
我的数据集如下所示:
Make: AUSTIN
Models:
1000
1300
Make: Ferrari
Models:
458
La Ferrari
我喜欢 JSON 格式,如下所示:
{
make: "AUSTIN",
models: [
{model: "1000"},
{model: "1300"}
]
},
{
make: "Ferrari",
models: [
{model: "458"},
{model: "La Ferrari"}
]
}
这是一个非常大的数据集,所以我无法手动完成。
网上找了一圈,没找到合适的。
提前致谢!
据我了解你的问题,我想回答一下。
你可以这样做。
function getFormatted(s){
const total = []
const lines = s.split('\n');
let index = 0;
while(lines[index]){
const make = lines[index];
const obj = {
make: make.replace('Make: ',''),
models: []
}
// index + 1 will be 'Models:'
let modelCurrentIndex = index + 2;
let currentModel = lines[modelCurrentIndex];
// Check until the next occurrence of 'Make: '
while(currentModel && !currentModel.startsWith("Make:")){
obj.models.push({model: currentModel});
modelCurrentIndex += 1;
currentModel = lines[modelCurrentIndex];
}
index = modelCurrentIndex;
total.push(obj);
}
return JSON.stringify(total);
}
示例网页如下所示
调用此函数后,
解释:
行的第一个索引应标识为 'make' 并且该索引 + 2 将被标识为模型的起点。
while 循环会将模型添加到对象中的数组,直到它识别出以 'Make:' 开头的行。
之后,移动索引并重复该过程。
Make sure you are entering the values with a line break!
我的数据集如下所示:
Make: AUSTIN
Models:
1000
1300
Make: Ferrari
Models:
458
La Ferrari
我喜欢 JSON 格式,如下所示:
{
make: "AUSTIN",
models: [
{model: "1000"},
{model: "1300"}
]
},
{
make: "Ferrari",
models: [
{model: "458"},
{model: "La Ferrari"}
]
}
这是一个非常大的数据集,所以我无法手动完成。
网上找了一圈,没找到合适的。
提前致谢!
据我了解你的问题,我想回答一下。
你可以这样做。
function getFormatted(s){
const total = []
const lines = s.split('\n');
let index = 0;
while(lines[index]){
const make = lines[index];
const obj = {
make: make.replace('Make: ',''),
models: []
}
// index + 1 will be 'Models:'
let modelCurrentIndex = index + 2;
let currentModel = lines[modelCurrentIndex];
// Check until the next occurrence of 'Make: '
while(currentModel && !currentModel.startsWith("Make:")){
obj.models.push({model: currentModel});
modelCurrentIndex += 1;
currentModel = lines[modelCurrentIndex];
}
index = modelCurrentIndex;
total.push(obj);
}
return JSON.stringify(total);
}
示例网页如下所示
调用此函数后,
解释:
行的第一个索引应标识为 'make' 并且该索引 + 2 将被标识为模型的起点。
while 循环会将模型添加到对象中的数组,直到它识别出以 'Make:' 开头的行。
之后,移动索引并重复该过程。
Make sure you are entering the values with a line break!