搜索json对象并返回确切位置

时间:2019-03-08 14:52:02

标签: json dart

我正在尝试以编程方式在JSON文件中搜索特定的章节号,并使其返回标题索引,章节索引和章节索引。最好的方法是什么?请参阅下面的JSON示例:

{
    "book": {
        "titles": [
            {
                "title_num": "1",
                "title_name": "First Title",
                "chapters": [
                    {
                        "chapter_num": "1",
                        "chapter_name": "First chapter",
                        "sections": [
                            {
                                "section_content": "This is the first section of chapter 1.",
                                "section_num": "1.01",
                                "section_title": "section title"
                            }
                        ]
                    }
                ]
            },
            {
                "title_num": "2",
                "title_name": "Second Title",
                "chapters": [
                    {
                        "chapter_num": "8",
                        "chapter_name": "Eighth chapter",
                        "sections": [
                            {
                                "section_content": "This is the first section of chapter 8.",
                                "section_num": "8.01",
                                "section_title": "section title"
                            },
                            {
                                "section_content": "This is the second section of chapter 8.",
                                "section_num": "8.02",
                                "section_title": "section title"
                            }
                        ]
                    }
                ]
            }

        ]
    }
}

1 个答案:

答案 0 :(得分:0)

假设您已将JSON解析为Dart值,我将执行以下操作:

List<int> sectionTitle(dynamic jsonData, String sectionNumber) {
  List titles = jsonData["book"]["titles"];
  for (int titleIndex = 0; titleIndex < titles.length; titleIndex++) {
    List chaptes = titles[titleIndex]["chapters"];
    for (int chapterIndex = 0; chapterIndex < chapters.length; chapterIndex++) { 
      List sections = chapters[chapterIndex]["sections"];
      for (int sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) {
        if (sections[sectionIndex]["section_num"] == sectionNumber) {
          return [titleIndex, chapterIndex, sectionIndex];
        }
      }
    }
  }
  return null;  // or: throw ArgumentError("section not present");
}

没什么,只是在JSON映射中找到列表,对其进行迭代(使用索引,因为您想返回它们),然后在找到结果时以某种方式返回所有三个索引。如果这是用于公共API,则我将为结果创建一个类,而不仅仅是返回一个列表,因为列表类型不能保证存在三个值。