Read JSON file in Custom Script

364 views
Skip to first unread message

Mats Brorson

unread,
Apr 30, 2021, 9:22:06 AM4/30/21
to NetBox
Need to load a JSON-file, and according to documentation there is a load_json method to do this.

Trying: data = json_load('file.json')

get an error:
<class 'NameError'>
name 'load_json' is not defined



Clearly I'm doing it wrong, and documentation these methods are missing. Suggestion?


Brian Candler

unread,
Apr 30, 2021, 9:33:24 AM4/30/21
to NetBox
What documentation did you see that in?  Can you provide the link?

Custom scripts are written in Python, so you use the Python standard libraries for reading json.  It's not really a Netbox question.

import json
res = None
with open("file.json") as f:
    res = json.load(f)

Christopher Mills

unread,
Apr 30, 2021, 11:29:01 AM4/30/21
to Mats Brorson, NetBox
Examining the code, load_json is a method of class BaseScript which is inherited by Script which your script should inherit from. Using this fact, load_json will be accessed as self.load_json(“filename”). But, it also looks like it expects a static json file in the scripts directory so isn’t the right function if you want to load arbitrary JSON submitted by the user. All the function does anyway is call the json.load() function as already given by Brian.

HTH

Sent from my iPhone

On 30 Apr 2021, at 14:22, Mats Brorson <ma...@brorson.se> wrote:


--
You received this message because you are subscribed to the Google Groups "NetBox" group.
To unsubscribe from this group and stop receiving emails from it, send an email to netbox-discus...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/netbox-discuss/f024ccfe-2d90-4210-a463-788966f71aa4n%40googlegroups.com.

Mats Brorson

unread,
May 1, 2021, 5:08:10 AM5/1/21
to NetBox
Ahh....been spending to much time writing code this week, so my brain missed the obvious "self." Thank Chris.

Brian, I know that i can use standard Python calls, but if I can shave some lines of code, I am happy. :-) Btw, load_json and load_yaml are actually documented at https://netbox.readthedocs.io/en/stable/additional-features/custom-scripts/ but really just mentioned.
Reply all
Reply to author
Forward
0 new messages