[英]How do I turn a piece of text into a parent children JSON file?
我想將其轉換為類似於Flare.json的內容 ,如下所示。
{"name": "ROOT",
"children": [
{"name": "Hemiptera",
"children": [
{"name": "Miridae",
"children": [
{"name": "Kanakamiris", "children":[]},
{"name": "Neophloeobia",
"children": [
{"name": "incisa", "children":[] }
]}
]}
]},
{"name": "Lepidoptera",
"children": [
{"name": "Nymphalidae",
"children": [
{"name": "Ephinephile",
"children": [
{"name": "rawnsleyi", "children":[] }
]}
]}
]}
]}
}
有沒有辦法我可以用Javascript,Python或R編程地做到這一點?
首先,讓我為您提出一種輸入格式。 可能是這樣的:
var kenyaConstitutionArray = ["1#SOVEREIGNTY OF CONSTITUTION", "1:1#All sovereign...", "1:2#...",....,"100#....","100:1#..."]
只有1#
代表章節, 1:1#
代表第1:1#
章的第一個子條款,而1:1:1#
代表第1:1:1#
章的第一個子條款。我使用#
是因為我假設它不會出現在文本中。
要獲取章節和子句,您需要執行以下操作:
var path = text.substr(0, text.indexOf('#'));//it will give path or levels
在這里,文本是數組的元素。 例如, text = kenyaConstitutionArray[1]
現在,您必須獲得以下章節:
var chapter = path.substr(0, path.indexOf(':'));
只需少量修改即可以相同方式獲取子條款,
並且,可以在循環中或遞歸地構建json。
另一種方法是:
對於輸入,您也可以使用嵌套數組。 喜歡:
var kenyaConstitution = [["chapter1",[["clause1", [["subclause1"], ["subclause2"]]],["clause2",[["subclause2-1"], ["subclause2-2"]]]]]];
將上述嵌套數組轉換為json對您來說非常容易。 在這種情況下,好的方法是使用遞歸。
編輯:
完整的代碼:
[忽略代碼中的注釋。]
<!DOCTYPE html>
<head>
<title>JSON</title>
<script>
function kenyaConstitutionToJSON() {
var kenyaConstitution = [["chapter1",[["clause1", [["subclause1"], ["subclause2"]]],["clause2",[["subclause2-1"], ["subclause2-2"]]]]]];
var kenyaChapterJSON;
var kenJSON = {};
kenJSON["name"] = "Constitution of Kenya";
kenJSON["children"] = [];
if(kenyaConstitution.length === 0) {
console.log("Constitution is empty! Please pass constitution through Parliament...");
return;
} else {
for (var chapter in kenyaConstitution) { //for each chapter return json
kenyaChapterJSON = convertToJSON(kenyaConstitution[chapter]) || {};
kenJSON["children"].push(kenyaChapterJSON);
}
}
return kenJSON;
}
function convertToJSON(constitutionArray) {
var obj = {};
//constitutionArray[item] = ["chapter1",[["clause1", [["subclause1"], ["subclause2"]]],["clause2",[["subclause2-1"], ["subclause2-2"]]]]]
obj["name"] = constitutionArray[0]; // {name: "children1", children=[ ]}
obj["children"] = [];
//if(constitutionArray.length > 0) {
for (var cl in constitutionArray[1]) {
var kenJSON1 = convertToJSON(constitutionArray[1][cl]);
obj["children"].push(kenJSON1);
}
//} else {
//obj["children"].push(constitutionArray[0]);
//}
return obj;
}
kenyaConstitutionToJSON();
</script>
</head>
<body>
</body>
在return kenJSON;
上放置斷點return kenJSON;
行並查看輸出。 就像:
OUTPUT:
{
"name":"Constitution of Kenya",
"children":[
{
"name":"chapter1",
"children":[
{
"name":"clause1",
"children":[
{
"name":"subclause1",
"children":[
]
},
{
"name":"subclause2",
"children":[
]
}
]
},
{
"name":"clause2",
"children":[
{
"name":"subclause2-1",
"children":[
]
},
{
"name":"subclause2-2",
"children":[
]
}
]
}
]
}
]
}
希望能對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.