【问题标题】:how to convert a CSV into JSON using Python Or Java. The csv is representation of a nested JSON (Containing array of json objects and nested objects)如何使用 Python 或 Java 将 CSV 转换为 JSON。 csv 是嵌套 JSON 的表示(包含 json 对象和嵌套对象的数组)
【发布时间】:2021-06-22 01:22:06
【问题描述】:

我得到一个 csv 文件,例如:

attrib1_x,attrib1_y,attrib1_z_0_p,attrib1_z_0_c,attrib1_z_1_p,attrib1_z_1_c,attrib2_R,attrib2_K,attrib3

1、2、100、200、500、600、222、320,你好


csv 表示如下所示的 json。


{
"attrib1":{
           "x":1,
           "y":2,
           "z":[{"p":100,"c":200},{"p":500,"c":600}]
          },
"attrib2":{"R":222,"K":320},
"attrib3":"hello"
}

所以基本上在这里我得到了上面的 CSV,并且需要将其转换为所示的 JSON 结构

。不知道该怎么做。是否有任何库(Python/Java)可以帮助我解决这个问题。

如果有任何具有不同 csv 标头的解决方案/建议也可以使用。我可以要求团队为我提供具有不同标题名称的 csv 来表示嵌套 / 数组。

【问题讨论】:

  • 您知道要构建的对象的结构还是需要从标题中提取它?在任何情况下,我都不认为它有一个库,但应该很容易构建每个对象,逐行解析文件。

标签: java python json csv


【解决方案1】:
JSONObject jsonObject = new JSONObject("{
"attrib1":{
           "x":1,
           "y":2,
           "z":[{"p":100,"c":200},{"p":500,"c":600}]
          },
"attrib2":{"R":222,"K":320},
"attrib3":"hello"
}");

试试看吧。 它可能会有所帮助

【讨论】:

  • #in python myDct={ "attrib1":{ "x":1, "y":2, "z":[{"p":100,"c":200}, {"p":500,"c":600}] }, "attrib2":{"R":222,"K":320}, "attrib3":"hello" } 用于 myDct.items 中的键、值(): 打印(键,值)
【解决方案2】:

首先你迭代key 然后类似地迭代value 并保存到csv中

  String eol = System.getProperty("line.separator");
                try(Writer writer = new FileWriter("C:\\Users\\m.hussain\\Desktop\\CSV\\testing.csv"))
                {
                    for (Map<String, Object> map : objectRecords)
                    {
                        for (Map.Entry<String, Object> entry : map.entrySet())
                        {
                            writer.append(entry.getKey())
                                    .append(',');
                        }
                        break;
                    }
                    writer.append(eol);
                    for (Map<String, Object> map : objectRecords)
                    {
                        for (Map.Entry<String, Object> entry : map.entrySet())
                        {
                            JSONObject jsonObject;
                            try
                            {
                                jsonObject = new JSONObject(String.valueOf(entry.getValue()));
                                writer.append(jsonObject.getString("value"));
                            }
                            catch (Exception e)
                            {
                                writer.append(String.valueOf(entry.getValue()));
                            }
                            writer.append(',');
                        }
                        writer.append(eol);
                    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-06
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 2016-12-11
    相关资源
    最近更新 更多