python中的JSON到JSONL

时间:2019-03-19 16:29:03

标签: python json python-3.x

OrderedDict([('attributes', OrderedDict([('type', 'SurveyQuestionResponse__c'), ('url', '<URL>')])), ('Id', 'a0V3600000ASsIGEA1'), ('IsDeleted', False), ('Name', 'Response-0092757'), ('CurrencyIsoCode', 'USD'), ('CreatedDate', '2017-09-15T07:00:00.000+0000'), ('CreatedById', '00536000004RpBDAA0'), ('LastModifiedDate', '2017-10-06T20:22:33.000+0000'), ('LastModifiedById', '00536000004RpBDAA0'), ('SystemModstamp', '2017-10-06T20:22:33.000+0000'), ('Survey_Question__c', 'a0X36000005D50OEAS'), ('SurveyTaker__c', 'a0W360000067bYmEAI'), ('Alias__c', '<username>'), ('Geography__c', 'AAAA'), ('Market__c', 'AAA'), ('Respondent_Type__c', 'Security - RSM'), ('Response__c', '5 minutes or less'), ('Score__c', 5.0), ('Site_Name__c', 'AAA001'), ('Vendor__c', '<Vendor Name>'), ('of_Time_Question_was_Responded_to__c', 1.0)])]

这是我在python中打印时导入的JSON。我正在使用jsonlines包尝试将其解析为jsonL,以便可以与redshift一起使用。

data = initialQuery['records']  #this gives me the above orderedDict           
            with jsonlines.open(localFilePath+fileName.format(nextObj,fileCount),  mode='w') as outfile :
                outfile.write_all(data)

这几乎让我回了需要的东西。问题在于它正在获取JSON的属性部分。我正在尝试删除属性部分,仅包含ID上的所有内容。

我尝试过:

del data['attributes']
data.pop("attributes")
for element in data :
    data.pop('attributes', None)
for element in data :
    del data['attributes']
for element in data :
    data.pop('type', None)
他们中没有一个人工作;我应该怎么做?

编辑: 我发布的答案不太正确;我只得到第一行,而不是当前记录集的所有行。

1 个答案:

答案 0 :(得分:0)

感谢评论者;这是我们的结局:

            data = initialQuery['records']
            item = data.pop()

            item.pop('attributes', None)
            tempdict = OrderedDict({})
            for k,v in item.items():
                tempdict[k.lower()] = v

            with open(localFilePath+fileName.format(nextObj,fileCount), 'w') as outfile :
                    outfile.write(json.dumps(tempdict))
                    outfile.write('\n')

这可能不是最有效的,但确实可以。您需要为此使用集合中的OrderedDict。

编辑:这只是给我JSONL到JSONL的第一行。它正在丢弃其他所有内容;回到绘图板。

Edit2:这是解决方法

for element in data :


        item = data.pop()
        item.pop('attributes', None)

        tempdict = OrderedDict({})
        for k,v in item.items() :
            if 'date' in k.lower() or 'stamp' in k.lower() :
                d = datetime.datetime.strptime(v,'%Y-%m-%dT%H:%M:%S.%f+0000')
                v = d.strftime('%Y-%m-%d %I:%M:%S')
                tempdict[k.lower()] = v
            else :
                tempdict[k.lower()] = v

        with open(localFilePath+fileName.format(nextObj,fileCount), 'a') as outfile :
            outfile.write(json.dumps(tempdict))
            outfile.write('\n')