简体   繁体   English

在 Python 中的 json 数据中添加随机值

[英]Add random values to json data in Python

I am new to python.I want read a json file and add random values to it.The json contains subset too.I am unable to solve this.我是 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 Expected Output 预计

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

This is performing:这是执行:

dictionary['loc'] = some_number

So you lose the nested dict that was already there.所以你失去了已经存在的嵌套字典。

You only want to modify keys that do not have a dict as a value.您只想修改没有 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

If your JSON can contain lists - you will need to handle that case too.如果您的 JSON 可以包含列表 - 您也需要处理这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM