如何在python中创建两级嵌套json?

时间:2019-03-09 21:50:42

标签: python json nested

我是一个新手,已经四天的时间了,找不到我需要的答案。

我的数据看起来像这样

ENTITY,MEASUREMENT_DATE,CHART_VALUE,PARAM
143,2019/03/08 10:21:21 PM,0.047353,param1
143,2019/03/08 10:21:21 PM,40.25,param2
160,2019/03/08 10:57:18 AM,0.066874,param1
160,2019/03/06 4:24:31 PM,38,param2
143,2019/03/06 10:00:41 PM,0.01707,param1
143,2019/03/09 1:04:32 AM,35.25,param2
160,2019/03/06 4:24:31 PM,0.048042,param1
143,2019/03/07 12:09:38 AM,0,param1
160,2019/03/08 10:57:18 AM,42.25,param2
143,2019/03/09 1:04:32 AM,0.012104,param1
143,2019/03/06 10:00:41 PM,41.75,param2
143,2019/03/07 12:09:38 AM,36.5,param2

,所需的输出应如下所示:

{
    "143": {
        "param1": {
            "MEASUREMENT_DATE": 
            "CHART_VALUE":
         }, 
         "param2": {
           "MEASUREMENT_DATE": 
            "CHART_VALUE": 
         },
     },
     "160": {
        "param1": {
            "MEASUREMENT_DATE": 
            "CHART_VALUE":
         }, 
         "param2": {
           "MEASUREMENT_DATE": 
            "CHART_VALUE": 
         },
     }, 
}

我已经尝试过此代码,但是对于初学者来说,我仍然没有按参数将分组归为一类。

with open('file.csv') as csvfile:
    r = DictReader(csvfile, skipinitialspace=True)
    data = [dict(d) for d in r]

    groups = []
    uniquekeys = []

    for k, g in groupby(data, lambda r: ( r['PARAM'])):
        groups.append({
            "group": k,
            "user": [{k: v for k, v in d.items() if k not in ['PARAM']} for d in list(g)]
        })
        uniquekeys.append(k)

感谢进阶!

1 个答案:

答案 0 :(得分:0)

您有一个根本性的问题,即您无法在示例中使用字典结构。

例如,您有两行,分别是“ 143”和“ param1”。字典不能在同一键上包含多个值。剩下两个选择(我认为)。您想要在每个位置存储一组结果,或者想要一种方法来选择一个值存储在该键上(例如按日期显示的最新值)。

尽管如此,这应该可以帮助您入门。这是存储键的所有值的解决方案:

from __future__ import print_function
from pprint import pformat
import csv
try:
  from io import StringIO
except:
  from StringIO import StringIO


data = '''ENTITY,MEASUREMENT_DATE,CHART_VALUE,PARAM
143,2019/03/08 10:21:21 PM,0.047353,param1
143,2019/03/08 10:21:21 PM,40.25,param2
160,2019/03/08 10:57:18 AM,0.066874,param1
160,2019/03/06 4:24:31 PM,38,param2
143,2019/03/06 10:00:41 PM,0.01707,param1
143,2019/03/09 1:04:32 AM,35.25,param2
160,2019/03/06 4:24:31 PM,0.048042,param1
143,2019/03/07 12:09:38 AM,0,param1
160,2019/03/08 10:57:18 AM,42.25,param2
143,2019/03/09 1:04:32 AM,0.012104,param1
143,2019/03/06 10:00:41 PM,41.75,param2
143,2019/03/07 12:09:38 AM,36.5,param2
'''

class JsonBuilder(object):
  def __init__(self):
    self.result = {}

  def ingest_row(self, row):
    primary_key, mdate, value, param = row
    if primary_key not in self.result:
      self.result[primary_key] = {}

    if param not in self.result[primary_key]:
      self.result[primary_key][param] = []

    self.result[primary_key][param].append({ 
        "MEASUREMENT_DATE": mdate,
         "CHART_VALUE": value })
  def __str__(self):
    return pformat(self.result)

builder = JsonBuilder()
reader = csv.reader(StringIO(data))
next(reader, None) #skip header
for row in reader:
 builder.ingest_row(row)
print(builder)

输出:

{'143': {'param1': [{'CHART_VALUE': '0.047353',
                     'MEASUREMENT_DATE': '2019/03/08 10:21:21 PM'},
                    {'CHART_VALUE': '0.01707',
                     'MEASUREMENT_DATE': '2019/03/06 10:00:41 PM'},
                    {'CHART_VALUE': '0',
                     'MEASUREMENT_DATE': '2019/03/07 12:09:38 AM'},
                    {'CHART_VALUE': '0.012104',
                     'MEASUREMENT_DATE': '2019/03/09 1:04:32 AM'}],
         'param2': [{'CHART_VALUE': '40.25',
                     'MEASUREMENT_DATE': '2019/03/08 10:21:21 PM'},
                    {'CHART_VALUE': '35.25',
                     'MEASUREMENT_DATE': '2019/03/09 1:04:32 AM'},
                    {'CHART_VALUE': '41.75',
                     'MEASUREMENT_DATE': '2019/03/06 10:00:41 PM'},
                    {'CHART_VALUE': '36.5',
                     'MEASUREMENT_DATE': '2019/03/07 12:09:38 AM'}]},
 '160': {'param1': [{'CHART_VALUE': '0.066874',
                     'MEASUREMENT_DATE': '2019/03/08 10:57:18 AM'},
                    {'CHART_VALUE': '0.048042',
                     'MEASUREMENT_DATE': '2019/03/06 4:24:31 PM'}],
         'param2': [{'CHART_VALUE': '38',
                     'MEASUREMENT_DATE': '2019/03/06 4:24:31 PM'},
                    {'CHART_VALUE': '42.25',
                     'MEASUREMENT_DATE': '2019/03/08 10:57:18 AM'}]}}