return 0 return 0 - 1 year ago 88
JSON Question

How to access the same JSON file from both javascript and python?

NOTE: This is not for web programming. We use javascript to interface with low level hardware, hence let's not go with jQuery APIs etc.

I have a javascript file that performs a sequence of actions on a device, and I have a python file that will be invoked later to validate these actions. There is a set of hardware information hard-coded in both javascript file and python file. I want to avoid this duplication of information by putting these info into a JSON file so both can access it.

// Javascript
var hardware_info = JSON.parse(load('hardware.json'));
// load() is probably not standard javascript API, but it basically copies that code into the existing script.

Already failed by this step because '
' is not using javascript syntax...

I already validated the json using jshint/jslint,
looks like this:

"hardware1": {
"ID": "xxx"
"hardware2": {
"ID": "yyy"

The following Python works well for accessing the json, there is not much to it:

with open('hardware.json', 'r') as f:
data = json.load(f)

Answer Source

It looks like load() executes the specified file, not read it and return the contents. If this is your only option to read another file, then I suggest you use JSONP instead of JSON.

JSONP works by adding a callback around the data. Instead of:

{"key": "value"}

the file contains a function call with the data being passed in:

callback({"key": "value"});

This is meant to be executed by a JavaScript engine, causing it to execute the callback. load() would execute your file, and the callback function would be called as a result, passing in the data.

When used on the web, you'd call a JSONP service and pass in the name of the callback the service should add, but when just sharing a configuration file between a JS engine and Python, you'd hardcode that callback name.

In Python, you'd have to strip off the callback text before loading it as JSON data. That could be as easy as just removing the first N and last M characters:

with open('hardware.json', 'r') as f:
    jsonp_data =
    # remove first 9 and last 3 characters to remove JSONP callback
    data = json.loads(jsonp_data[9:-3])

A little more sophisticated technique could use newlines:

{"key": "value"}

to make it easier to remove the first and last line in Python. Or you could use jsonp_data.partition('(')[-1].jsonp.rpartition(')')[0] to take everything between the first ( and the last ) character in the string. Etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download