简体   繁体   English

如何在输出随机json的代码中添加循环并将其保存在本地?

[英]How to add loop in this code that outputs random json and save it in local?

wrote a code using faker library in python that generates random json strings. 使用python中的faker库编写了一个代码,该代码生成随机的json字符串。 how to add another loop in it so ids will loop in ids place 如何在其中添加另一个循环,以便ID将在ID位置循环

import json 
from faker import Faker
import random
from random import randint

ids=(1,2,3,4,5,6)

print('{"data": [')
fake = Faker('en_US')
for _ in range(10):
    sms =  {
      "pid": "ABs-1cd",
      "body": fake.text(),
      "mime": fake.ean(),
      "hashed": fake.ean(),
      "celus": fake.ean(),
      "ids": "1", 
      "dev": "465p"
   }
    print(",")
    print(json.dumps(sms))

print('],"ids": "1"}') 

and save the json according to user id like in case 1.json,2.json,3.json,4.json 并根据用户ID保存json,如情况1.json,2.json,3.json,4.json

I think this is what you are looking for: 我认为这是您要寻找的:

ids= (1, 2, 3, 4, 5, 6)

fake = Faker('en_US')

for ind in ids:
    cont = []
    for idx in range(10):
        sms =  {
            "pid": "ABs-1cd",
            "body": fake.text(),
            "mime": fake.ean(),
            "hashed": fake.ean(),
            "celus": fake.ean(),
            "ids": ind, 
            "dev": "465p"
        }
        cont.append(sms)

    f_name = '{}.json'.format(ind)
    with open(f_name, 'w') as fp:
        json.dump(cont, fp, indent=4)
        print('saved {}'.format(f_name))

The outer loop iterates over the numbers 1 until 6, where each outer-loop iteration generates <id_number>.json . 外循环迭代数字1到6,其中每个外循环迭代生成<id_number>.json The inner-loop creates 10 python dictionaries and saves them in a list called cont , which is emptied at the beginning of the outer loop. 内部循环创建10个python字典并将它们保存在名为cont的列表中,该列表在外部循环的开头被清空。

To begin with, instead of the two print statement, you can append all dictionaries to a list, and then create your overall dictionary, 首先,您可以将所有字典附加到列表中,而不是两个print语句,然后创建整体字典,

Also you can add another outer loop which loops through the indexes and picks id accordingly 您也可以添加另一个外部循环,循环遍历索引并相应地选择id

import json 
from faker import Faker
import random
from random import randint

ids=[1,2,3,4,5,6]

data = {}
li = []

fake = Faker('en_US')
for idx in range(400):
    #Loop through id in ids
    id = ids[int(idx%6)]
    sms =  {
      "pid": "ABs-1cd",
      "body": fake.text(),
      "mime": fake.ean(),
      "hashed": fake.ean(),
      "celus": fake.ean(),
      "ids": id,
      "dev": "465p"
   }
    li.append(sms)

data['data'] = li
print(data)

The output will be 输出将是

{'data': 
[{'pid': 'ABs-1cd', 'body': 'Between voice list option have. Grow yet smile citizen. After item play food lay.\nWoman same key. Join change choice market remain rise system.\nAlong that every piece. Smile face not.', 'mime': '1654036516104', 'hashed': '2183375261370', 'celus': '3745268243000', 'ids': 1, 'dev': '465p'}, 
{'pid': 'ABs-1cd', 'body': 'Politics no exist either discuss our draw. Crime mean loss there.', 'mime': '6907925600497', 'hashed': '4357683719153', 'celus': '6068299372691', 'ids': 2, 'dev': '465p'}, 
{'pid': 'ABs-1cd', 'body': 'Four cup charge. Cold wall fight himself direction coach case. Moment beyond produce prove black action.', 'mime': '0252898756297', 'hashed': '7548395540624', 'celus': '5079227810636', 'ids': 3, 'dev': '465p'}, {'pid': 'ABs-1cd', 'body': 'Area individual side eye amount artist. Side change former during pull skin. Half worker season after message travel town thousand.\nPublic end who. Summer enter key base.', 'mime': '9405000561321', 'hashed': '1072256350153', 'celus': '1521369156270', 'ids': 4, 'dev': '465p'}, {'pid': 'ABs-1cd', 'body': 'Film wide would pressure blue. Method guess while air deep. Response court make month however.', 'mime': '8541314383028', 'hashed': '3528769482198', 'celus': '2763098895122', 'ids': 5, 'dev': '465p'}, 
{'pid': 'ABs-1cd', 'body': 'Alone response detail operation. Less show crime maybe.\nLater popular agent stage number decide. Tv soldier nation member executive wrong close. Authority true popular gun student usually plant.', 'mime': '3013043458964', 'hashed': '5340459977450', 'celus': '7274348458516', 'ids': 6, 'dev': '465p'}, 
{'pid': 'ABs-1cd', 'body': 'Note PM value stand sure only test. During seem bring situation wife.\nBreak different difficult so. Leader include per catch. Attorney base card.', 'mime': '4625296268772', 'hashed': '3945698717878', 'celus': '8227765580925', 'ids': 1, 'dev': '465p'}, ....

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

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