[Fixed]-Django load local json file

43👍

Use the json module:

import json

json_data = open('/static/prices.json')   
data1 = json.load(json_data) # deserialises it
data2 = json.dumps(data1) # json formatted string

json_data.close()

See here for more info.

As Joe has said, it’s a better practice to use fixtures or factories for your test data.

👤DanS

9👍

The trick here is to use python’s built-in methods to open that file, read its contents and parse it using the json module

i.e.

import json

data = open('/static/prices.json').read() #opens the json file and saves the raw contents
jsonData = json.loads(data) #converts to a json structure

4👍

👤Joe

Leave a comment