I have a JSON file (input.json) like the following which has 2 rows… (The real one has more than 1m rows)
JavaScript
x
3
1
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"}
2
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"}
3
I want to basically change the value of each and every field with name four to a random value, so basically wherever it appears, it will remove what it currently have and change it to a random given value:
expected output:
JavaScript
1
3
1
{"one":"A1","two":"B2","three":"C3","four":"random123","five":"E5"}
2
{"one":"ZZ","two":"YY","three":"XX","four":"akskaskas","five":"VV","six":"UU"}
3
It could be any random value..
I’m kinda struggling with python at the moment, any tips or solutions would really help!
JavaScript
1
11
11
1
from random import choices
2
import json
3
4
with open('input.json') as infile:
5
data = json.load(infile)
6
7
data['four'] = ''.join(choices('asdf1234', k=10))
8
9
with open('output.json', 'w') as outfile:
10
json.dump(data, outfile)
11
Advertisement
Answer
You need to change your input file structure, the elements must be on a list, like this:
JavaScript
1
10
10
1
[
2
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
3
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
4
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
5
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
6
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
7
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
8
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"}
9
]
10
You can change a key value with this:
JavaScript
1
11
11
1
from random import choices
2
import json
3
4
with open('input.json') as infile:
5
data = json.load(infile)
6
for i in data:
7
i['four'] = ''.join(choices('asdf1234', k=10))
8
9
with open('output.json', 'w') as outfile:
10
json.dump(data, outfile)
11
choices
method will randomly choose 10 characters from ‘asdf1234’, join
will create a single string, and the result will be store into four
key.