【问题标题】:How do I convert Python output results to JSON string using Python如何使用 Python 将 Python 输出结果转换为 JSON 字符串
【发布时间】:2018-02-27 07:36:32
【问题描述】:

这是我的函数调用

if __name__ == '__main__':

    a = head_tail()
    b = data_info_for_analysis()
    c = data_visualization_chart()
    d = missing_values_duplicates()
    e = mapping_yes_no()
    f = one_hot_encoding()
    g = outlier_identification()

    out2 = removing_outliers()
    h = droping, features = removing_unwanted_columns(out2)

    df_telecom_test, df_telecom_train, probs, clf = random_model_predictions(droping, features)

    i = logistic_model_prediction(df_telecom_train, df_telecom_test, features)
    j = decision_model_prediction(df_telecom_train, df_telecom_test, features)

    k = fpr_tpr_thresholds(df_telecom_test, probs, clf, features)

我正在尝试将该对象保存为 json 文件

filter = "JSON File (*.json)|*.json|All Files (*.*)|*.*||"
filename = a.SaveFileName("Save JSON file as", filter)

if filename:
    with open(filename, 'w') as f:
        json.dump(a, f)

我收到以下错误

Traceback (most recent call last):
  File "/home/volumata/PycharmProjects/Churn-Analysis/sample-object-json.py", line 429, in <module>
    filename = a.SaveFileName("Save JSON file as", filter)
AttributeError: 'NoneType' object has no attribute 'SaveFileName'

我也试过另一种方法

def head_tail():
    ### Head of the data
    print(df_telecom.head(5))

    ### Tail of the data
    print(df_telecom.tail(5))

code_obj = head_tail()
dis.disassemble(code_obj)

尝试上述方法后,出现此错误

cell_names = co.co_cellvars + co.co_freevars
AttributeError: 'NoneType' object has no attribute 'co_cellvars'

【问题讨论】:

  • 这个问题很不清楚。你现在有什么?
  • 我需要将我的 python 结果转换为 json 字符串。我该怎么做,我不知道如何将其转换为 json 结果
  • 如果你的输出像 dict/list 一样是 json 可序列化的,你可以使用 json 模块来转储你的结果
  • 我正在将结果转换为 JSON
  • 你需要返回结果(不是打印),然后使用json.dumps(result)

标签: python json output analysis


【解决方案1】:

要将pandas.DataFrame 序列化为 JSON,您可以使用其to_json() 方法。有不同的格式选项:

>>> df
   0  1
0  a  b
1  c  d
>>> df.to_json()
'{"0":{"0":"a","1":"c"},"1":{"0":"b","1":"d"}}'
>>> df.to_json(orient='values')
'[["a","b"],["c","d"]]'

【讨论】:

    【解决方案2】:

    你的问题很不清楚。如果你只是想从 python-standard-types 转换一些数据,你可以简单地use json.dump:

    someResults = { ... }
    
    import json
    with open("file.txt", "w") as f:
         json.dump(someResults, f, indent=4)
    

    【讨论】:

    • 那个“someResults”作为一个函数存在,那么如何传递该函数以获取json文件
    • @sangeethasivakumar: someResults 只是一个样本变量,因为在我发布此答案时,您没有提供任何有关您的结构的详细信息。 someResults 可以包含任何内容 - 它只是一个占位符。
    • 是的,我知道它是一个变量......我告诉我我的输出结果存储为一个函数而不是变量。我正在研究如何将函数传递给 json 字符串。
    • 好吧,然后在函数中返回你的输出:temp = functioncall(),在函数中你需要使用return。见:The return Statement
    • 我已经在我的函数代码中使用了这个return语句......我无法将python代码结果转换为json文件。
    猜你喜欢
    • 1970-01-01
    • 2015-02-19
    • 2021-03-07
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多