int updatearr( const char * input, json_t **root)
{
//set array
json_t *interface_element, *portinfo_obj;
json_t *arr = json_object_get(*root, "interfaces");
if(json_is_array(arr))
{
//index 1 is hardcoded for simplicity
interface_element = json_array_get(arr, 1);
if(NULL == interface_element)
{
fprintf(stderr, "update_sysconfig_attr: Error updating \"ip_address\" in %s \n", "./network_sysconfig.cfg");
json_decref(arr);
return -1;
}
else
{
//now we are inside interfaces array, we select ip_address key.
portinfo_obj = json_object_get(interface_element, "ip_address");
if(NULL == portinfo_obj)
{
fprintf(stderr, "update_sysconfig_attr: Error updating \"ip_address\" in %s \n",
"./network_sysconfig.cfg");
json_decref(interface_element);
json_decref(arr);
return -1;
}
else
{
// here we set our intended value for ip_address
if( -1 == json_string_set(portinfo_obj, input) )
{
fprintf(stderr, "update_sysconfig_attr: Error updating \"ip_address\" in %s \n",
cfg_fortiiot_networkconf);
json_decref(portinfo_obj);
json_decref(interface_element);
json_decref(arr);
return -1;
}
}
}
}
json_decref(portinfo_obj);
json_decref(interface_element);
json_decref(arr);
return 0;
}
int main(int argc, char *argv[])
{
json_error_t json_error;
json_t *root =
json_load_file("./sysconfig.cfg",0,&json_error); //load JSON file
updatearr( newipnum, &root);
if(0 != json_dump_file(root, "./network_sysconfig.cfg", JSON_INDENT(4)))
{
fprintf(stderr, "File Error\n"); //I cant properly write to my file. The resulting file is shown below.
}
json_decref(root);
return 1;
}
Resulting file:
The resulting file is broken until interfaces and I get a -1 return value to json_dump_file()
{
"hostname": "defaulthostname",
"gateway": "192.168.1.1",
"interfaces": [
Am I updating my array/file incorrectly?
Is it due to the fact that I called json_decref() to my json objects inside my updatearr() function?
I am assuming this is ok since I passed root as pass by reference?
Thank in advance!