簡體   English   中英

在 Python 中的 json 數據中添加隨機值

[英]Add random values to json data in Python

我是 python 的新手。我想讀取 json 文件並向其中添加隨機值。json 也包含子集。我無法解決這個問題。

sample.json

{"name": "Kash","age": 12,"loc": {"loc1":"Uk","loc2":"Usa"}}






import json
import random
f=open("sample.json")
data=json.load(f)


def iterate(dictionary):
    for key, value in dictionary.items():
        dictionary[key]=random.randrange(1,10)
        print(dictionary)
        if isinstance(value, dict):
            iterate(value)
    return dictionary

iterate(data)





Output I Got

{'name': 8, 'age': 12, 'loc': {'loc1': 'tc', 'loc2': 'cbe'}}
{'name': 8, 'age': 6, 'loc': {'loc1': 'tc', 'loc2': 'cbe'}}
{'name': 8, 'age': 6, 'loc': 9}
{'loc1': 5, 'loc2': 'cbe'}
{'loc1': 5, 'loc2': 1}

============================================

Output 預計

{"name": 15,"age": 85,"loc": {"loc1":52,"loc2":36}}
dictionary[key] = random.randrange(1,10)

這是執行:

dictionary['loc'] = some_number

所以你失去了已經存在的嵌套字典。

您只想修改沒有 dict 作為值的鍵。

def iterate(dictionary):
    for key, value in dictionary.items():
        if isinstance(value, dict):
            iterate(value)
        else:
            dictionary[key] = random.randrange(1, 10)
    return dictionary

如果您的 JSON 可以包含列表 - 您也需要處理這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM