Search code examples
javascriptjqueryjsonjson2html

json2html how to deal with special characters (e.g. @) in json keys


The JSON response returned by a RESTful API contains the @ symbol for some keys and other keys are made in this manner ("document.title").

My piece of JSON looks like this.

"fields": {
  "document.content_type": [
    "application/ms-word"
  ],
  "document.name": [
    "zh1.docx"
  ],
  "@title": [
    "The History of the Pencil"
  ],
  "@date": [
    "2016-01-13T07:30:25-0500"
  ],
  "document.content": [
    "some text goes here"
  ],
  "@guid": [
    "76c99131-23b1-4435-9b93-eaabd9e33a67"
  ]
}

In normal JavaScript/jQuery, I easily can access these values by doing fields["@title"][0] to get the title or fields["document.content"][0] to get the document content, but this format does not work in the json2html transform.

For instance, this code in the transform does not work.

{"tag":"h4","html":"${fields['document.name'].0}"}

Can anybody point me to how I can in the json/html transform access those special json tags. I know in some cases I can change the tags to be in a more standard format, but what if I cannot change them or for some reason they need to remain as such?


Solution

  • json2html transform splits string inside ${} by ".". You can change keys to be compatible with transform, eg.:

    for(var k in data.fields){
      if(k.match(/\./)){
        data.fields[k.replace(/\./g, '_')] = data.fields[k];
      }
    }
    

    Plunk