Select Page

I had a task to create a mechanism to load sample data so that we could do some demonstrations. Our incoming data is in JSON format so I took a bunch of requests and put them into individual text files. The next task was to create a little Python program to choose one of the files randomly, take the JSON and send it into our system.

Using glob, I get a list of the filenames that match the mask of “*.json”. The choice() function is a handy little tool. It chooses and returns a random element from the list. That gives us a random file from out of the working directory.

In the case of this task I needed to load read the JSON, make some minor changes, and then send into the system, using a cURL command. So, next we read from the selected file and make a little example modification:

Next, I wanted to write the modified JSON to a unique file so that I could pass that into cURL. I had considered using a TemporaryFile, but I wanted to be able to close the file and make sure it’s written to disk without deleting the file first (because I need to pass it to cURL).

Next, we’re ready to post the file and clean up our little mess of a temporary file.

Pretty straightforward overall. Here’s the whole source file. Have at it!

Share This