【问题标题】:Editing String and dictionary output from JSON file从 JSON 文件编辑字符串和字典输出
【发布时间】:2018-02-02 02:52:51
【问题描述】:

我有一个程序,它接收一个 JSON 文件,逐行读取它,根据时间将时间聚合到四个 bin 中,然后将其输出到文件中。但是,由于将字典与字符串连接,我的文件输出包含额外的字符。

例如,一行的输出如下所示:

dwQEZBFen2GdihLLfWeexA<bound method DataFrame.to_dict of            Friday  Monday  Saturday  Sunday  Thursday  Tuesday  Wednesday
Category                                                                 
Afternoon       0       0         3       2         2        0          1
Evening        20       4        16      11         4        3          5
Night          16       1        19       5         2        5          3>

内存地址也被连接到输出文件中。

这是用于创建此特定文件的代码:

import json
import ast
import pandas as pd
from datetime import datetime

def cleanStr4SQL(s):
    return s.replace("'","`").replace("\n"," ")

def parseCheckinData():
    #write code to parse yelp_checkin.JSON
    # Add a new column "Time" to the DataFrame and set the values after left padding the values in the index

    with open('yelp_checkin.JSON') as f:
        outfile = open('checkin.txt', 'w')
        line = f.readline()
#        print(line)
        count_line = 0
        while line:
            data = json.loads(line)
#            print(data)
#            jsontxt = cleanStr4SQL(str(data['time']))
            # Parse the json and convert to a dictionary object

            jsondict = ast.literal_eval(str(data))
            outfile.write(cleanStr4SQL(str(data['business_id'])))

            # Convert the "time" element in the dictionary to a pandas DataFrame
            df = pd.DataFrame(jsondict['time'])

            # Add a new column "Time" to the DataFrame and set the values after left padding the values in the index
            df['Time'] = df.index.str.rjust(5, '0')

            # Add a new column "Category" and the set the values based on the time slot
            df['Category'] = df['Time'].apply(cat)

            # Create a pivot table based on the "Category" column
            pt = df.pivot_table(index='Category', aggfunc=sum, fill_value=0)

            # Convert the pivot table to a dictionary to get the json output you want
            jsonoutput = pt.to_dict
#            print(jsonoutput)
            outfile.write(str(jsonoutput))

            line = f.readline()
            count_line+=1
    print(count_line)
    outfile.close()
    f.close()

# Define a function to convert the time slots to the categories
def cat(time_slot):
    if '06:00' <= time_slot < '12:00':
        return 'Morning'
    elif '12:00' <= time_slot < '17:00':
        return 'Afternoon'
    elif '17:00' <= time_slot < '23:00':
        return 'Evening'
    else:
        return 'Night'

我想知道是否可以通过某种方式从输出文件中删除内存位置?

感谢任何建议,如果您需要更多信息,请告诉我。

感谢您的阅读

【问题讨论】:

    标签: python json dictionary file-io formatting


    【解决方案1】:

    您使用 JSON 的方式似乎是流式传输,即unpleasant problem to deal with

    如果您不使用非常大的 JSON 文件,则最好使用

    with open("input.json", "r") as input_json: json_data = json.load(input_json)

    然后根据需要从json_data 中提取特定条目(记住它是一个字典),操作它们并填充一个要保存的输出字典

    另外,在 python 中,如果你使用 with open(...) 语法,你 don't need 之后会关闭文件

    【讨论】:

      【解决方案2】:

      问题 1:to_dict 后面缺少括号,导致出现这个“内存地址”。

      问题 2:要生成有效的 JSON,您还需要将输出包装到数组中

      问题 3:使用str 或 eval 将 JSON 转换为字符串是不安全的。使用json.loads().dumps()

      import json
      
          ...
          line_chunks = []
          outfile.write("[")
          while line:
              ...
              jsondict = json.loads(data)  # problem 3
              ...
              jsonoutput = pt.to_dict()  # problem 1
              ...
          outfile.write(json.dumps(line_chunks))  # problems 2 and 3
      

      【讨论】:

      • 这很有趣,我不知道您必须将 JSON 包装在一个数组中。此外,当我尝试执行 json.loads(data) 时,它会出现此错误: JSONDecodeError: Expecting property name 用双引号括起来。由于某种原因,在加载数据后,它会将双引号替换为单引号。
      • 一般来说,你不必将 JSON 包装在一个数组中,但是在这里你从输入文件的每一行生成一个字典结构,所以如果有超过一行,它会粘合两个字典一起。结果({key: value}{key: value} 之类的东西不是有效的 JSON。因此,它需要转换为[{key: value}, {key: value}] 之类的东西
      • 哦,好的,谢谢您提供的信息和代码帮助!我没有意识到还有其他错误。
      猜你喜欢
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      相关资源
      最近更新 更多