【问题标题】:Formating adding nested dictionary to JSON file in specific format格式化以特定格式将嵌套字典添加到 JSON 文件
【发布时间】:2020-10-02 16:29:06
【问题描述】:

我的 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": "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"
    }
]

【问题讨论】:

  • 嗨@JGio,欢迎来到SO。我对 python 的了解不多,但如果我理解我认为你想创建对象数组。试试这个例子: import json # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = [json.loads(x )] # 结果是一个 Python 字典: print(y)

标签: json python-3.x dictionary


【解决方案1】:

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"
    }
]

【讨论】:

    【解决方案2】:

    您可能需要更改一些内容:

    1. 您需要将 data_table 类型更改为列表。
    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
    

    【讨论】:

    • 无法附加到 JSON。查看您的输出文件。
    猜你喜欢
    • 2019-09-24
    • 1970-01-01
    • 2020-05-03
    • 2021-04-09
    • 1970-01-01
    • 2016-03-24
    • 2015-05-20
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多