Home > Net >  For loop repeat to get larger json data with no duplicate in Python
For loop repeat to get larger json data with no duplicate in Python

Time:12-29

I tried to repeat 10times of json file which add 1~10 at element called "ProcessGuid" in each iteration via the following code

import json
file = open("D:/Test/test.json",'r',encoding='utf-8')
papers = []
for line in file.readlines():
    dic = json.loads(line)
    papers.append(dic)
    
result_int = papers
string_name = list(map(str, range(1,10)))
    
for element in string_name:
    result = []
    result = result_int
    processlist = []
    for i in range(len(result)):
        (result[i])['Event']['EventData']['ProcessGuid'] = str((result[i])['Event']['EventData']['ProcessGuid']) element
    
    with open("D:/Test/process_" str(element) ".json", 'w', encoding ='utf8') as json_file:
        json.dump(result, json_file, ensure_ascii = False) 

I though the result of data in each repeat would be like (suppose the origin data element of ProcessGuid is Hello)

1st repeat : ProcessGuid = Hello1
2nd repeat : ProcessGuid = Hello2
3rd repeat : ProcessGuid = Hello3
...
10th repeat : ProcessGuid = Hello10

But the result is the following

1st repeat : ProcessGuid = Hello1
2nd repeat : ProcessGuid = Hello12
3rd repeat : ProcessGuid = Hello123
...
10th repeat : ProcessGuid = Hello12345678910

Where do I get wrong? Thanks.

CodePudding user response:

You keep overwriting result_int over and over again.

How do I clone a list so that it doesn't change unexpectedly after assignment?

Change:

result = list(result_int)

CodePudding user response:

For each element, the code appends to the same values. If you only want to append each element once to the original values, you could save the original values first:

base_values = [str(paper['Event']['EventData']['ProcessGuid']) for paper in papers]

for element in string_name:
    for i, paper in enumerate(papers):
        paper['Event']['EventData']['ProcessGuid'] = base_values[i]   element
    
    with open("D:/Test/process_"   str(element)   ".json", 'w', encoding ='utf8') as json_file:
        json.dump(papers, json_file, ensure_ascii = False) 
  • Related