0

I want to map my Input JSON with another JSON using mustache.

My Input JSON is like:

{
  "data": [
    { "catalogId": "1850", "productId": "ELEC004A"},
    { "catalogId": "1851", "productId": "PNG679"}
  ]
}

I want a template in which I could combine the mustache tags with my output json.

var template = JSON.stringify(
  {
    Product: [
      {{#data}}
      {
        productId:'{{productId}}',
        parentProductId:'{{catalogId}}'
      }
      {{/data}} 
    ]
  }
);

I tried this but using mustache tag with JSON are giving me errors. I tried defining the template without using JSON.stringify but no luck!

Have to use mustache only as it is the requirement, the actual input JSON is quite large and can't map it using the traditional way.

Abhishek
  • 880
  • 12
  • 28
  • What is your desired output? and why moustache? why not just regular javascript code? – Tamas Hegedus Jul 19 '16 at 11:10
  • 2
    You might want to check your code formatting. – evolutionxbox Jul 19 '16 at 11:10
  • @TamasHegedus My desired output is a JSON mentioned in the template with mustache tags replaced with relevant data from my input JSON – Abhishek Jul 19 '16 at 11:19
  • To my understanding the argument you pass to JSON.stringify() is interpreted as an Object but contains mustache tags (such as {{#data}}). That results in incorrect JSON syntax. Convert the template to a string and do not use JSON.stringify() – Stefan Reimers Jul 19 '16 at 11:48
  • @StefanReimers yes you are right! But even if I remove stringify and do a normal toString I get `unexpected token { on {{#data}}` – Abhishek Jul 19 '16 at 11:59
  • Maybe this might help: var template = ` { Product: [ {{#data}} { productId:'{{productId}}', parentProductId:'{{catalogId}}' } {{/data}} ] }`; – Stefan Reimers Jul 19 '16 at 12:10

1 Answers1

0

My desired output is a JSON mentioned in the template with mustache tags replaced with relevant data from my input JSON

You don't need moustache here.

var input = {
  "data": [
    { "catalogId": "1850", "productId": "ELEC004A"},
    { "catalogId": "1851", "productId": "PNG679"}
  ]
};

var output = {
  Product: input.data.map(item => ({
    productId: item.productId,
    parentProductId: item.catalogId
  }))
};

console.log(output);
Tamas Hegedus
  • 24,663
  • 9
  • 48
  • 87
  • I need to do it using mustache only, This is just a sample JSON my actual JSON is pretty large can't map it using the traditional technique. – Abhishek Jul 19 '16 at 11:41
  • I'm afraid that's the harder way to do, and more error prone. Lets see what can we do about it – Tamas Hegedus Jul 19 '16 at 12:00
  • @Abhishek Moustache is not capable of this. You cannot generate for example comma separated lists. All you are going to end up with is 50% boilerplate and workaround code besides the template. see http://stackoverflow.com/questions/6114435/in-mustache-templating-is-there-an-elegant-way-of-expressing-a-comma-seperated-l – Tamas Hegedus Jul 19 '16 at 12:05