Skip to content
Advertisement

Replace each reoccuring string value of a one line flat json to a random value using python

I have a JSON file (input.json) like the following which has 2 rows… (The real one has more than 1m rows)

{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"}
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"}

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:

{"one":"A1","two":"B2","three":"C3","four":"random123","five":"E5"}
{"one":"ZZ","two":"YY","three":"XX","four":"akskaskas","five":"VV","six":"UU"}

It could be any random value..

I’m kinda struggling with python at the moment, any tips or solutions would really help!

from random import choices
import json

with open('input.json') as infile:
  data = json.load(infile)

data['four'] = ''.join(choices('asdf1234', k=10))

with open('output.json', 'w') as outfile:
    json.dump(data, outfile)

Advertisement

Answer

You need to change your input file structure, the elements must be on a list, like this:

[
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
{"one":"A1","two":"B2","three":"C3","four":"D4","five":"E5"},
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"},
{"one":"ZZ","two":"YY","three":"XX","four":"WW","five":"VV","six":"UU"}
]

You can change a key value with this:

from random import choices
import json

with open('input.json') as infile:
    data = json.load(infile)
    for i in data:
        i['four'] = ''.join(choices('asdf1234', k=10))

with open('output.json', 'w') as outfile:
    json.dump(data, outfile)

choices method will randomly choose 10 characters from ‘asdf1234’, join will create a single string, and the result will be store into four key.

Advertisement