Copyright (C) Kevin Larke 2009-2020

This file is part of libcm.

libcm is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

libcm is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

See the GNU General Public License distributed with the libcm package or look here: .


//
// cmJsonTest() demonstrates some JSON tree operations.
//
cmJsRC_t cmJsonTest( const char* fn, cmCtx_t* ctx )
{
  cmJsRC_t      rc  = kOkJsRC;
  cmJsRC_t      rc1 = kOkJsRC;
  cmJsonH_t     h   = cmJsonNullHandle;
  cmJsonH_t     h1  = cmJsonNullHandle;
  void*         sbp = NULL;
  unsigned      sbn = 0;
  cmJsonNode_t* np  = NULL;
  cmRpt_t*      rpt = &ctx->rpt;
  
  // initialize an empty JSON tree
  if((rc = cmJsonInitialize(&h,ctx)) != kOkJsRC )
    goto errLabel;
  
  // load the tree from a file
  if((rc = cmJsonParseFile(h,fn,NULL)) != kOkJsRC )
    goto errLabel;
  
  // print the tree
  cmJsonReport(h);
  
  // find an array member named 'mem14'
  if((np = cmJsonFindValue(h,"mem14",NULL,kArrayTId)) == NULL )
    cmRptPrint(rpt,"'mem14' not found.\n");
  else
  {
    cmRptPrint(rpt,"'mem14' found.\n");
    cmJsonPrintTree(np,rpt);
  }
  
  // remove the array node from the tree
  cmJsonRemoveNode(h,np, true);
  cmRptPrint(rpt,"mem14 removed.\n");
  
  // print the tree with the array node removed
  cmJsonPrintTree( cmJsonRoot(h), rpt );
  
  // serialize the tree into a dynamically allocated
  // buffer sbp[sbn].  
  if((rc = cmJsonSerializeTree(h,NULL,&sbp,&sbn)) != kOkJsRC )
    goto errLabel;
  else
    cmRptPrint(rpt,"***Serialize Ok.****\n");
  
  // initialize an empty JSON tree
  if((rc = cmJsonInitialize(&h1,ctx)) != kOkJsRC )
    goto errLabel;
  
  // deserialize sbp[sbn] into the empty tree
  if((rc = cmJsonDeserialize(h1,sbp,NULL)) != kOkJsRC )
    goto errLabel;
  else
  {
    cmJsonPrintTree( cmJsonRoot(h1),rpt);
    cmRptPrint(rpt,"***Deserialize Ok.****\n");
  }
  
  // find an member node named 'mem5'
  if((np = cmJsonFindValue(h,"mem5",NULL,0)) == NULL )
    cmRptPrint(rpt,"mem5 not found.");
  
  // merge two sub-trees
  if( cmJsonMergeObjectNodes( h, np->u.childPtr, 
  np->u.childPtr->siblingPtr) != kOkJsRC )
  {
    cmRptPrint(rpt,"merge failed.");
  }
  else
  {
    cmJsonReport(h);
  }
  
  errLabel:
  
  // release the JSON trees
  rc = cmJsonFinalize(&h);
  rc1 = cmJsonFinalize(&h1);
  
  return rc == kOkJsRC ? rc1 : rc;
}