格式化以特定格式将嵌套字典添加到JSON文件

时间:2020-10-02 16:29:06

标签: json python-3.x dictionary

我的Python脚本正在运行,并追加到我的JSON文件中;但是,我尝试添加带编号的条目标识,但没有成功。另外,每次迭代计算时,我都试图获得特定的输出。寻找详细的示例和指导。

当前的Python脚本

import json

# Dictionary All-Calculations
def dict_calc(num1, num2):
    add = str(float(num1)+float(num2))
    sub = str(float(num1)-float(num2))
    mul = str(float(num1)*float(num2))
    div = str(float(num1)/float(num2))
    calc_d = {"Add" : add, "Subtract" : sub, "Multiply" : mul, "Divide" : div}
    return calc_d

# Yes or No
def y_n(answer):
    if answer[:1] == 'y':
        return True
    if answer[:1] == 'n':
        return False

# Main Dictionary
data_table = {}

while True:
    num1 = input("\n     Enter first number: ")
    num2 = input("\n     Enter second number: ")
    data_table = dict_calc(num1, num2)
    with open('dict_calc.json', 'a', encoding='utf-8') as f:
        json.dump(data_table, f, ensure_ascii=True, indent=4)
    answer = input("\n     Run Again? (Y/N) ").lower().strip()
    if y_n(answer) == True:
        continue
    else:
        print("\n     Thank You and Goodbye")
        break

当前输出示例

{
    "Add": "579.0",
    "Subtract": "-333.0",
    "Multiply": "56088.0",
    "Divide": "0.26973684210526316"
}{
    "Add": "1245.0",
    "Subtract": "-333.0",
    "Multiply": "359784.0",
    "Divide": "0.5779467680608364"
}{
    "Add": "1396.0",
    "Subtract": "554.0",
    "Multiply": "410475.0",
    "Divide": "2.315914489311164"
}

所需的输出示例-我试图添加Entry加上数字,每次迭代后都会增加。另外,我也在尝试模拟相同的输出。

[
    {
        "Entry": "1",
        "Add": "579.0",
        "Subtract": "-333.0",
        "Multiply": "56088.0",
        "Divide": "0.26973684210526316"
    },
    {
        "Entry": "2",
        "Add": "1245.0",
        "Subtract": "-333.0",
        "Multiply": "359784.0",
        "Divide": "0.5779467680608364"
    },
    {
        "Entry": "3",
        "Add": "1396.0",
        "Subtract": "554.0",
        "Multiply": "410475.0",
        "Divide": "2.315914489311164"
    }
]

2 个答案:

答案 0 :(得分:0)

JSON是一个嵌套结构。您不能简单地向其附加更多数据。为此,请参见JSON Lines格式。

如果使用常规JSON格式,则必须读入整个JSON结构,对其进行更新,然后再次将其完全写出,或者在结构完成后直接将其写入。

示例:

import json

# Dictionary All-Calculations
def dict_calc(num1, num2, entry):
    add = str(float(num1)+float(num2))
    sub = str(float(num1)-float(num2))
    mul = str(float(num1)*float(num2))
    div = str(float(num1)/float(num2))
    calc_d = {"Entry": str(entry), "Add" : add, "Subtract" : sub, "Multiply" : mul, "Divide" : div}
    return calc_d

# Yes or No
def y_n(answer):
    if answer[:1] == 'y':
        return True
    if answer[:1] == 'n':
        return False

# Empty List that will hold dictionaries.
data_table = []

entry = 0 # for tracking entry numbers
while True:
    num1 = input("\n     Enter first number: ")
    num2 = input("\n     Enter second number: ")

    # Count entry and add it to dictionary list.
    entry += 1
    data_table.append(dict_calc(num1, num2, entry))

    answer = input("\n     Run Again? (Y/N) ").lower().strip()
    if y_n(answer) == True:
        continue
    else:
        print("\n     Thank You and Goodbye")

        # Write the complete list of dictionaries in one operation.
        with open('dict_calc.json', 'w', encoding='utf-8') as f:
            json.dump(data_table, f, ensure_ascii=True, indent=4)
        break

输出:

[
    {
        "Entry": "1",
        "Add": "3.0",
        "Subtract": "-1.0",
        "Multiply": "2.0",
        "Divide": "0.5"
    },
    {
        "Entry": "2",
        "Add": "8.0",
        "Subtract": "-1.0",
        "Multiply": "15.75",
        "Divide": "0.7777777777777778"
    },
    {
        "Entry": "3",
        "Add": "13.399999999999999",
        "Subtract": "-2.2",
        "Multiply": "43.68",
        "Divide": "0.717948717948718"
    }
]

答案 1 :(得分:0)

您可能需要更改的几件事:

  1. 您需要将data_table类型更改为list。
  2. 您需要向其附加dict_calc函数结果。
  3. 添加柜台

这是您的代码:

import json

# Dictionary All-Calculations
def dict_calc(counter, num1, num2):
    add = str(float(num1)+float(num2))
    sub = str(float(num1)-float(num2))
    mul = str(float(num1)*float(num2))
    div = str(float(num1)/float(num2))
    calc_d = {"Entry": str(counter), "Add" : add, "Subtract" : sub, "Multiply" : mul, "Divide" : div}
    return calc_d

# Yes or No
def y_n(answer):
    if answer[:1] == 'y':
        return True
    if answer[:1] == 'n':
        return False

# Main Dictionary
data_table = []
counter = 1

while True:
    num1 = input("\n     Enter first number: ")
    num2 = input("\n     Enter second number: ")
    data_table.append( dict_calc(counter, num1, num2))
    counter += 1 
    with open('dict_calc.json', 'a', encoding='utf-8') as f:
        json.dump(data_table, f, ensure_ascii=True, indent=4)
    answer = input("\n     Run Again? (Y/N) ").lower().strip()
    if y_n(answer) == True:
        continue
    else:
        print("\n     Thank You and Goodbye")
        break