json parser

This commit is contained in:
Olof hagsand 2016-08-15 09:29:22 +02:00
parent 20087932c5
commit 887d43428b
15 changed files with 830 additions and 209 deletions

View file

@ -262,164 +262,6 @@ xml2cli(FILE *f,
return retval;
}
/*! Internal function to translate from xml tree to JSON
* @param[in,out] cb Cligen buffer to write to
* @param[in] x XML tree to translate from
* @param[in] level Indentation level
* @param[in] eq
* @param[in] comma
* @retval 0 OK
* @retval -1 Error
* XXX ugly code could be cleaned up
*/
static int
xml2json1_cbuf(cbuf *cb,
cxobj *x,
int level,
int eq,
int comma)
{
cxobj *xe = NULL;
cxobj *x1;
int retval = -1;
int level1 = level+1;
int level2 = level+2;
int i;
int n;
int eq1;
switch(xml_type(x)){
case CX_BODY:
cprintf(cb, "\"%s\"", xml_value(x));
break;
case CX_ELMNT:
if (eq == 2)
cprintf(cb, "%*s", 2*level2, "");
else{
cprintf(cb, "%*s", 2*level1, "");
cprintf(cb, "\"%s\": ", xml_name(x));
}
if (xml_body(x)!=NULL){
if (eq==1){
cprintf(cb, "[\n");
cprintf(cb, "%*s", 2*level2, "");
}
}
else {
cprintf(cb, "{\n");
}
xe = NULL;
n = xml_child_nr(x);
eq1 = 0;
for (i=0; i<n; i++){
xe = xml_child_i(x, i);
if (xml_body(xe)!=NULL){
if ((x1 = xml_child_i(x, i+1)) != NULL){
if (xml_body(x1) && strcmp(xml_name(xe), xml_name(x1)) == 0){
if (!eq1)
eq1 = 1;
}
else
if (eq1)
eq1 = 2; /* last */
}
}
if (xml2json1_cbuf(cb, xe, level1, eq1, (i+1<n)) < 0)
goto done;
if (xml_body(xe)!=NULL){
if (eq1 == 2){
cprintf(cb, "\n");
cprintf(cb, "%*s", 2*level2, "");
cprintf(cb, "]");
}
if (i+1<n)
cprintf(cb, ",");
cprintf(cb, "\n");
}
if (eq1==2)
eq1 = 0;
}
if (tleaf(x)){
}
else{
cprintf(cb, "%*s}", 2*level1, "");
if (comma)
cprintf(cb, ",");
cprintf(cb, "\n");
}
break;
default:
break;
}
// cprintf(cb, "%*s", 2*level, "");
retval = 0;
done:
return retval;
}
/*! Translate an XML tree to JSON in a CLIgen buffer
*
* @param[in,out] cb Cligen buffer to write to
* @param[in] x XML tree to translate from
* @param[in] level Indentation level
* @retval 0 OK
* @retval -1 Error
*
* @code
* cbuf *cb;
* cb = cbuf_new();
* if (xml2json_cbuf(cb, xn, 0, 1) < 0)
* goto err;
* cbuf_free(cb);
* @endcode
* See also xml2json
*/
int
xml2json_cbuf(cbuf *cb,
cxobj *x,
int level)
{
int retval = 1;
cprintf(cb, "{\n");
if (xml2json1_cbuf(cb, x, level, 0, 0) < 0)
goto done;
cprintf(cb, "}\n");
retval = 0;
done:
return retval;
}
/*! Translate from xml tree to JSON and print to file
* @param[in] f File to print to
* @param[in] x XML tree to translate from
* @param[in] level Indentation level
* @retval 0 OK
* @retval -1 Error
*
* @code
* if (xml2json(stderr, xn, 0) < 0)
* goto err;
* @endcode
*/
int
xml2json(FILE *f,
cxobj *x,
int level)
{
int retval = 1;
cbuf *cb;
if ((cb = cbuf_new()) ==NULL){
clicon_err(OE_XML, errno, "cbuf_new");
goto done;
}
if (xml2json_cbuf(cb, x, level) < 0)
goto done;
retval = 0;
done:
return retval;
}
/*! Validate a single XML node with yang specification
* - If no value and mandatory flag set in spec, report error.