javascript - make JSON attributes keys links on the first level

前端 未结 2 1301
梦毁少年i
梦毁少年i 2021-01-27 05:45

I need to prettify some JSON to display within an HTML

 section.

The working javascript code I use is..

function transformJson(k,         


        
相关标签:
2条回答
  • 2021-01-27 06:08

    Simply adding this after JSON.parse did the trick..

    var newObj = {};
    
    for(var attr in jsonObj){
        if( jsonObj[attr].constructor != Object && attr != 'href'){
            newObj['<a href="/documentation#'+attr+'">'+attr+'</a>'] = jsonObj[attr];
        }else{
            newObj[attr] = jsonObj[attr];
        }
    }
    

    (And then clearly JSON.stringify applied to newObj)

    0 讨论(0)
  • 2021-01-27 06:23

    Topmost object is passed to function provided as parameter for JSON.parse() under empty key. You need to include that in your transformJson:

    function transformJson(k, v) {
      if (k === 'href' && typeof v === 'string') {
        var label = v.replace(/&/gi, '&amp;');
        return '<a href=' + v + '>' + label + '</a>';
      } else if (k === '') {
        for (var x in v) {
          //skipping 'href' because it's handled by previous 'if'
          if (x !== 'href' && typeof v[x] === 'string') {
            var label = v[x].replace(/&/gi, '&amp;');
            v[x] = '<a href=/documentation#' +  x  + '>' + label + '</a>';
          }
        }
      }
      return v;
    }
    
    0 讨论(0)
提交回复
热议问题