Consuming Content API JSON v2

by nathanlogan

HTML

<div id="render"></div>

CSS

section.hwMessage {
  font-family: Helvetica, sans-serif;
  margin: 20px;
  color: #333;
}
p {
  padding: 10px;
  border: 1px solid #ccc;
}
strong {
  font-size: 1.2em;
  font-weight: bold;
  text-transform: uppercase;
  color: #8B0000;
}

JavaScript

const mapContent = function(item) {
  // single item (e.g. the top node)
  if (item.element) return componentFactory(item)

  // array of items
  const newItems = item && item.map((item, index) => {
    return componentFactory(item)
  })
  return newItems.join(' ')
}


const componentFactory = function(obj) {
  switch (obj.element) {
    case 'hwMessage':
    	return `<section class="hwMessage">${mapContent(obj.content)}</section>`
    
    case 'hwMessageBody':
    case 'hwMessageSection':
      return mapContent(obj.content)

		case 'p':
      return `<p>${mapContent(obj.content)}</p>`

    case 'hwEmphasis':
    case 'b':
      return `<strong>${mapContent(obj.content)}</strong>`

    // example of object we'll just ignore (along with their children)
    case 'topicmeta':
    case 'titlealts':
    case 'prolog':
    case 'section.meta-data':
      return

    case '$text':
      return obj.content

    default:
      return mapContent(obj.content)
  }
}


const json = {
	"element": "hwMessage",
    "attributes": {
        "id": "FF84CDC0-430F-529C-BD30-108769DFFD4C",
        "outputclass": "HwBoilerplate",
        "xml:lang": "en-CA",
        "class": "- topic/topic concept/concept hwMessage/hwMessage ",
    },
	"content": [{
        "element": "hwMessageBody",
        "attributes": {
            "class": "- topic/body concept/conbody hwMessageBody/hwMessageBody "
        },
        "content": [{
            "element": "hwMessageSection",
            "attributes": {
                "id": "0463782D-8732-4409-86A7-BC4E6E59E677",
                "class": "- topic/section hwMessage/hwMessageSection "
            },
            "content": [{
                "element": "p",
                "attributes": {
                    "class": "- topic/p "
                },
                "content": [
                    {
                        "element": "hwEmphasis",
                        "attributes": {
                            "id":...