sdawood / json-tots

JSON Template of Templates
MIT License
9 stars 4 forks source link

Question: Iterating over array elements #2

Closed dilipv21 closed 5 years ago

dilipv21 commented 5 years ago

Thanks for the tots !! it's very helpful in mapping JSONS !!

Query : Null check on array elements before ittirating.

Document: { "a" : 1, "b" : [ { x : 10, y: 12 }, { x : 10, y: 12 }] }

Template: { "A" : {{a}}, "B" : [ "{%%{b}}", { "X" : {{x}}, "Y" : {{x}} } ] }

Scenario : When the Document doesn't have the "b" and if we try to transform it results in Error occurred while transforming data Error: Inception Operator [%] should be used for template nodes yielding an array.

Is there a way to check null or avoid above scenario ?

Thanks Dilip

sdawood commented 5 years ago

Thanks for your report.

Off the top of my head, you can default 'b' from some named source, e.g. 'default'

I'll research better options and update soon.

For example: var tots = require("json-tots") const document = { "a" : 1, "bx" : [ { x : 10, y: 12 }, { x : 10, y: 12 }] }

const template = { "A" : '{{a}}', "B" : [ "{?=default %%{b}}", { "X" : '{{x}}', "Y" : '{{x}}' } ] }

const options = {sources: {default: {b: []}}}

const result = tots.transform(template, options)(document)

console.log(result)

sdawood commented 5 years ago

TIP

In general I recommend that you keep the options json that you use with a particular template transformation along with the template in the same versioned json text file.

Of course here we talk about the 'values' part of the options, with no runtime references.

You can merge later as such:

const options = {... loadedOptione, ... runtime options}

tots.transform(template, options)(document)

Hope that helps.

dilipv21 commented 5 years ago

Thanks for the response. Yes, it worked fine 👍 Can the option be json path? as i have nested path use case.

Example : const options = {sources: {default: {<json-path>: []}}}

Example: with nested path:

var tots = require("json-tots"); const document = {"D" : { "a" : 1 }}; const template = { "A" : '{{D.a}}', "B" : [ "{?=default %%{D.b}}", { "X" : '{{x}}', "Y" : '{{x}}' } ] }; const options = {sources: {default: {'D.b': []}}}; const result = tots.transform(template, options)(document); console.log(result);

dilipv21 commented 5 years ago

Also, default to replace any element independent of json path.