如何使用 Python 将 Python 输出结果转换为 JSON 字符串

How do I convert Python output results to JSON string using Python

这是我的函数调用

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-standard-types 转换一些数据,你可以简单地 use json.dump:

someResults = { ... }

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

要将 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"]]'