Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django load local json file

I have an ajax view:

def ajax_prices(request):
    data = {'data':'data'}
    return HttpResponse(json.dumps(data), mimetype='application/json')

I want to test this with a local json file (prices.json). How can I import a local json file?

Local json file 'prices.json'

{"aaData": [
[1, "70.1700", "2008-12-29 11:23:00"],
[2, "70.2600", "2008-12-29 16:22:00"],
[3, "70.6500", "2008-12-30 11:30:00"],
[4, "70.8700", "2008-12-30 16:10:00"],
[5, "70.5500", "2009-01-02 11:09:00"],
[6, "70.6400", "2009-01-02 16:15:00"],
[7, "70.6500", "2009-01-05 11:17:00"]
]}

I can't do that with:

data = '/static/prices.json'
like image 997
nelsonvarela Avatar asked May 08 '12 12:05

nelsonvarela


People also ask

How do I read a JSON file?

JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.

How do I read a JSON file in Python?

json.loads(): If you have a JSON string, you can parse it by using the json.loads() method.json.loads() does not take the file path, but the file contents as a string, using fileobject.read() with json.loads() we can return the content of the file. Example: This example shows reading from both string and JSON file.


2 Answers

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.

like image 102
DanS Avatar answered Sep 22 '22 15:09

DanS


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
like image 29
g19fanatic Avatar answered Sep 24 '22 15:09

g19fanatic