简体   繁体   中英

Generate Random json data using python

Need to generate random json data in this format

list=['20','30','50','1','200']

for n in list : 
    data= 
          {
           "total_members_present":1000    
           "count": n  
           "total_members_now":980 
         }


.........

it should continue until the list ends.

Using a simple iteration.

Ex:

lst = ['20','30','50','1','200']
result = []
start = 1000
for i in lst:
    data = {
           "total_members_present":start,    
           "count": i,
           "total_members_now":start - int(i)
          }
    start = data["total_members_now"]
    result.append(data)

print(result)

Output:

[{'count': '20', 'total_members_now': 980, 'total_members_present': 1000},
 {'count': '30', 'total_members_now': 950, 'total_members_present': 980},
 {'count': '50', 'total_members_now': 900, 'total_members_present': 950},
 {'count': '1', 'total_members_now': 899, 'total_members_present': 900},
 {'count': '200', 'total_members_now': 699, 'total_members_present': 899}]

Straightforwardly:

Don't use Python reserved names as variables ( list , dict etc) to avoid them being obscured .

lst = ['20','30','50','1','200']
start_num = 1000
data = []

for n in map(int, lst):
    data.append({
           "total_members_present": start_num,
           "count": n,
           "total_members_now": start_num - n
          })
    start_num -= n

print(data)

The output:

[{'count': 20, 'total_members_now': 980, 'total_members_present': 1000},
 {'count': 30, 'total_members_now': 950, 'total_members_present': 980},
 {'count': 50, 'total_members_now': 900, 'total_members_present': 950},
 {'count': 1, 'total_members_now': 899, 'total_members_present': 900},
 {'count': 200, 'total_members_now': 699, 'total_members_present': 899}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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