How to create and save Json Data in the JSON Store via a global script
-
Hi folks, whilst writing some config for a job I thought everyone who likes to use the Json Store might appreciate this global script I threw together:
function JsonObjectInstance(xid) { this.jsonXid = xid; this.jsonDataDao = com.serotonin.m2m2.db.dao.JsonDataDao.instance; this.jsonDataVo = {}; this.createNewInstance = function() { print("createNewInstance") //it's not instantiated, create a new one this.jsonDataVo = new com.serotonin.m2m2.vo.json.JsonDataVO; var mangoPermissions = new com.infiniteautomation.mango.permission.MangoPermission(2); //set to 1 for superadmin this.jsonDataVo.setXid(this.jsonXid ); this.jsonDataVo.setName(this.jsonXid ); this.jsonDataVo.setReadPermission( mangoPermissions );//superadmin by default this.jsonDataVo.setEditPermission( mangoPermissions );//superadmin by default var objectMapper = com.serotonin.m2m2.Common.getBean(com.fasterxml.jackson.databind.ObjectMapper.class, "daoObjectMapper"); var newJsonData = objectMapper.readTree('{}'); //default '{}' // If objectmapper is not used before saving, all objects get saved as an array. this.jsonDataVo.setJsonData(newJsonData); // this.jsonDataVo.save(newJsonData); //Mango3 this.jsonDataDao.insert(this.jsonDataVo);//mango4 }; //GET JSON STORE this.getJsonStore = function(data) { this.jsonDataVo = this.jsonDataDao.getByXid( this.jsonXid ); if(!this.jsonDataVo || this.jsonDataVo===null) { this.createNewInstance(); if(data) { var objectMapper = com.serotonin.m2m2.Common.getBean(com.fasterxml.jackson.databind.ObjectMapper.class, "daoObjectMapper"); var newJsonData = objectMapper.readTree('{}'); //default '{}' //If objectmapper is not used before saving, all objects get saved as an array. this.jsonDataVo.setJsonData(newJsonData); // this.jsonDataDao.save(this.newJsonData); //Mango3 this.jsonDataDao.insert(this.jsonDataVo);//mango4 } } }; this.getJsonStore(); this.getJsonData = function() { if(!this.jsonDataVo) { this.getJsonStore(); } var jsonString = ""; if(this.jsonDataVo.getJsonData) jsonString = this.jsonDataVo.getJsonData(); return jsonString; }; this.setJsonData = function(obj) { var objectMapper = com.serotonin.m2m2.Common.getBean(com.fasterxml.jackson.databind.ObjectMapper.class, "daoObjectMapper"); var newJsonData = objectMapper.readTree(JSON.stringify(obj)); //default '{}' this.jsonDataVo.setJsonData(newJsonData); // this.jsonDataDao.save(this.jsonDataVo) //Mango3 this.jsonDataDao.update( this.jsonDataVo , this.jsonDataVo);//mango4 }; }
If the json store object doesn't exist, it'll create it. Refer to example below to use...
var jsonObj = new JsonObjectInstance("VM_LIST"); jsonObj.setJsonData({key:"Tes2t",value:9000}) print(jsonObj.getJsonData()) // {"key":"Tes2t","value":9000}
Fox