【问题标题】:how to parse json which has key's value inside string with aray如何用数组解析在字符串中具有键值的json
【发布时间】:2021-01-24 14:34:55
【问题描述】:

这是我要解析的json

{ "vendorcategory": [
            {
                "id": "ctg-1",
                "_cO": 1598431685530,
                "_dL": 1,
                "name": "Fruits & Vegetables",
                "value": "[ { \"id\":\"ctg-1A\", \"name\":\"Fresh Vegetables\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1A-1\", \"name\":\"Potato, Onion, Tomato\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-2\", \"name\":\"Leafy Vegetables\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-3\", \"name\":\"Root Vegetables\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-4\", \"name\":\"Cucumber & Capsicum\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-4\", \"name\":\"Cabbage & Cauliflower\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-5\", \"name\":\"Beans, Brinjals & Okra\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-6\", \"name\":\"Gourd, Pumpkin, Drumstick\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1A-7\", \"name\":\"Specialty\", \"iKey\":\"Blobkey\" } ] }, { \"id\":\"ctg-1B\", \"name\":\"Herbs & Seasonings\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1B-1\", \"name\":\"Lemon, Ginger & Garlic\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1B-2\", \"name\":\"Indian & Exotic Herbs\", \"iKey\":\"Blobkey\" } ] }, { \"id\":\"ctg-1C\", \"name\":\"Fresh Fruits\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1C-1\", \"name\":\"Mangoes\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1C-2\", \"name\":\"Bananna, Sopota & Papaya\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1C-3\", \"name\":\"Apples & Pomegranate\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1C-4\", \"name\":\"Kivi, Melon, Citrus fruit\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1C-5\", \"name\":\"Seasonal Fruits\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1C-6\", \"name\":\"Fruit Baskets\", \"iKey\":\"Blobkey\" } ] }, { \"id\":\"ctg-1D\", \"name\":\"Exotic Fruits & Veggies\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1D-1\", \"name\":\"Exotic Fruits\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1D-2\", \"name\":\"Exotic Vegetables\", \"iKey\":\"Blobkey\" } ] }, { \"id\":\"ctg-1E\", \"name\":\"Organic Fruits & Vegetables\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1E-1\", \"name\":\"Organic Vegetables\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1E-2\", \"name\":\"Organic Fruits\", \"iKey\":\"Blobkey\" } ] }, { \"id\":\"ctg-1F\", \"name\":\"Cuts & Sprouts\", \"iKey\":\"Blobkey\", \"value\":[ {\"id\":\"ctg-1F-1\", \"name\":\"Cut & Peeled Veggies\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1F-2\", \"name\":\"Cut Fruits, Tender Coconut\", \"iKey\":\"Blobkey\" }, {\"id\":\"ctg-1F-3\", \"name\":\"Fresh Salads & Sprouts\", \"iKey\":\"Blobkey\" } ] } ]"
            }
        ]}

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 使用来自 dart:convert 的 jsonDecode

标签: json string flutter


【解决方案1】:

这是飞镖解决方案。您可以使用@Arty 的概念。

如果你注意到value 实际上是一个字符串。

所以你可以先解析整个 JSON,然后再从 value 变量中解析它。

所以,这里是第一个解析第一个 JSON 的数据模型

import 'dart:convert';

Category categoryFromJson(String str) => Category.fromJson(json.decode(str));

String categoryToJson(Category data) => json.encode(data.toJson());

class Category {
    Category({
        this.vendorcategory,
    });

    List<Vendorcategory> vendorcategory;

    factory Category.fromJson(Map<String, dynamic> json) => Category(
        vendorcategory: List<Vendorcategory>.from(json["vendorcategory"].map((x) => Vendorcategory.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "vendorcategory": List<dynamic>.from(vendorcategory.map((x) => x.toJson())),
    };
}

class Vendorcategory {
    Vendorcategory({
        this.id,
        this.cO,
        this.dL,
        this.name,
        this.value,
    });

    String id;
    int cO;
    int dL;
    String name;
    String value;

    factory Vendorcategory.fromJson(Map<String, dynamic> json) => Vendorcategory(
        id: json["id"],
        cO: json["_cO"],
        dL: json["_dL"],
        name: json["name"],
        value: json["value"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "_cO": cO,
        "_dL": dL,
        "name": name,
        "value": value,
    };
}

现在 Category 类包含 Vendorcategory 项目。而 Vendorcategory 包含 value 变量中的第二个 JSON。

这是第二个 JSON 的第二个数据类

List<ValueItem> valueItemFromJson(String str) => List<ValueItem>.from(json.decode(str).map((x) => ValueItem.fromJson(x)));

String valueItemToJson(List<ValueItem> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ValueItem {
    ValueItem({
        this.id,
        this.name,
        this.iKey,
        this.value,
    });

    String id;
    String name;
    String iKey;
    List<ValueItem> value;

    factory ValueItem.fromJson(Map<String, dynamic> json) => ValueItem(
        id: json["id"],
        name: json["name"],
        iKey: json["iKey"],
        value: json["value"] == null ? null : List<ValueItem>.from(json["value"].map((x) => ValueItem.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "iKey": iKey,
        "value": value == null ? null : List<dynamic>.from(value.map((x) => x.toJson())),
    };
}

现在调用这个函数

var ven = category[0]
List<ValueItem> = valueItemFromJson(ven.value)

您将获得价值列表项。

愉快的编码

【讨论】:

  • 不懂dart,但貌似只有静态类型?所以你不能只说object = json.parse(string) 并从json 中获取包含嵌套内容的完整对象?就像 Python 代码中的一行一样。
【解决方案2】:

我的下一个解决方案是使用 Python 语言,一开始并没有注意到这不是 Python 问题,如果您只需要一次性转换文件,仍然可以使用我的简单脚本。

在将值从字符串转换为对象时,您可以使用下一个代码将输入 json 文件重新转换为输出 json 文件。

此外,在使用下一个脚本之前,您必须确保您的输入文件是有效的 json,this site 可用于查找和修复输入 json 文件中的语法错误。

Try it online!(在左侧窗格中查找 output.json 生成的文件,以及 input.json)。

import json

with open('input.json', 'r', encoding = 'utf-8') as f:
    obj = json.loads(f.read())
    
obj['vendorcategory'][0]['value'] = json.loads(obj['vendorcategory'][0]['value'])

with open('output.json', 'w', encoding = 'utf-8') as f:
    f.write(json.dumps(obj, indent = 4, ensure_ascii = False))

转换结果输出示例:

{
    "vendorcategory": [
        {
            "id": "ctg-1",
            "_cO": 1598431685530,
            "_dL": 1,
            "name": "Fruits & Vegetables",
            "value": [
                {
                    "id": "ctg-1A",
                    "name": "Fresh Vegetables",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1A-1",
                            "name": "Potato, Onion, Tomato",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-2",
                            "name": "Leafy Vegetables",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-3",
                            "name": "Root Vegetables",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-4",
                            "name": "Cucumber & Capsicum",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-4",
                            "name": "Cabbage & Cauliflower",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-5",
                            "name": "Beans, Brinjals & Okra",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-6",
                            "name": "Gourd, Pumpkin, Drumstick",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1A-7",
                            "name": "Specialty",
                            "iKey": "Blobkey"
                        }
                    ]
                },
                {
                    "id": "ctg-1B",
                    "name": "Herbs & Seasonings",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1B-1",
                            "name": "Lemon, Ginger & Garlic",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1B-2",
                            "name": "Indian & Exotic Herbs",
                            "iKey": "Blobkey"
                        }
                    ]
                },
                {
                    "id": "ctg-1C",
                    "name": "Fresh Fruits",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1C-1",
                            "name": "Mangoes",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1C-2",
                            "name": "Bananna, Sopota & Papaya",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1C-3",
                            "name": "Apples & Pomegranate",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1C-4",
                            "name": "Kivi, Melon, Citrus fruit",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1C-5",
                            "name": "Seasonal Fruits",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1C-6",
                            "name": "Fruit Baskets",
                            "iKey": "Blobkey"
                        }
                    ]
                },
                {
                    "id": "ctg-1D",
                    "name": "Exotic Fruits & Veggies",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1D-1",
                            "name": "Exotic Fruits",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1D-2",
                            "name": "Exotic Vegetables",
                            "iKey": "Blobkey"
                        }
                    ]
                },
                {
                    "id": "ctg-1E",
                    "name": "Organic Fruits & Vegetables",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1E-1",
                            "name": "Organic Vegetables",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1E-2",
                            "name": "Organic Fruits",
                            "iKey": "Blobkey"
                        }
                    ]
                },
                {
                    "id": "ctg-1F",
                    "name": "Cuts & Sprouts",
                    "iKey": "Blobkey",
                    "value": [
                        {
                            "id": "ctg-1F-1",
                            "name": "Cut & Peeled Veggies",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1F-2",
                            "name": "Cut Fruits, Tender Coconut",
                            "iKey": "Blobkey"
                        },
                        {
                            "id": "ctg-1F-3",
                            "name": "Fresh Salads & Sprouts",
                            "iKey": "Blobkey"
                        }
                    ]
                }
            ]
        }
    ]
}

【讨论】:

  • 我认为他正在寻找 dart 而不是 python 的解决方案
  • @ShudiptoTrafder 刚刚注意到这一点。对不起。我指示 StackOverflow 向我展示 python 问题,但不知何故,这个非 python 出现了,我没有注意到这一点。但如果他只需要一次性转换,我的 Python 解决方案也很合适。
  • @ManuSingh 欢迎您! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
相关资源
最近更新 更多