Json值转换成JavaScript

时间:2018-11-28 22:31:31

标签: javascript html mysql json html5

最近刚开始学习Javascript,并大量阅读了有关JSON及其优点的信息。我正在做自己的小项目,并希望获得帮助。我想将JSON值纳入JavaScript代码中,但无法正常工作。我尝试使用以下命令进行解析:var obj = JSON.parse(txt);,但这没有用。下面是我的代码,可以更好地演示我的问题。

<body >
<h1>  person2</h1>
 <div class="koko">
     <div id="hh1" class="oee"></div>
 
    <div id="hh2" class="gauge" data-value="  // here the value of json  "></div><br>
	<div id="gg3" class="gauge"></div><br>
    <div id="hh4" class="gauge"></div>
  </div>  

  
  <script src="raphael-2.1.4.min.js"></script>
  <script src="justgage.js"></script>
  <script>
  document.addEventListener("DOMContentLoaded", function(event) {

    var dflt = {
      min: 0,
      max: 100,
   //   donut: true,
      gaugeWidthScale: 1.1,
      counter: true,
      hideInnerShadow: true
    }

    var hh1 = new JustGage({
      id: 'hh1',
      value:   , // here the value of json
      title: 'Kalle ',
      defaults: dflt
    });

    var hh2 = new JustGage({
      id: 'hh2',
      title: 'Pekka',
      defaults: dflt
    });
	
	    var hh3 = new JustGage({
      id: 'hh3',
      value:  , // here the value of json
      title: 'Jussi',
      defaults: dflt
    });
	
	    var hh4 = new JustGage({
      id: 'hh4',
      value:   , // here the value of json for Simba
      title: 'Simba',
      defaults: dflt
    });

  });
  
  </script>
</body>
values= '{"Kalle" : 75, "Pekka" : 59, "Jussi" : 8, "Simba" : 95}';

1 个答案:

答案 0 :(得分:1)

您需要先将values字符串解析为JSON,然后才能访问属性。

var hh1 = new JustGage({
      id: 'hh1',
      value:   (JSON.parse(values)).Kalle, // here the value of json
      title: 'Kalle ',
      defaults: dflt
    });

    var hh2 = new JustGage({
      id: 'hh2',
      title: 'Pekka',
      defaults: dflt
    });

        var hh3 = new JustGage({
      id: 'hh3',
      value:  (JSON.parse(values)).Jussi, // here the value of json
      title: 'Jussi',
      defaults: dflt
    });

        var hh4 = new JustGage({
      id: 'hh4',
      value:   (JSON.parse(values)).Simba, // here the value of json for Simba
      title: 'Simba',
      defaults: dflt
    });

  });

或类似的东西

values = JSON.parse(values);

var hh1 = new JustGage({
      id: 'hh1',
      value:   values.Kalle, // here the value of json
      title: 'Kalle ',
      defaults: dflt
    });

    var hh2 = new JustGage({
      id: 'hh2',
      title: 'Pekka',
      defaults: dflt
    });

        var hh3 = new JustGage({
      id: 'hh3',
      value:  values.Jussi, // here the value of json
      title: 'Jussi',
      defaults: dflt
    });

        var hh4 = new JustGage({
      id: 'hh4',
      value:   values.Simba, // here the value of json for Simba
      title: 'Simba',
      defaults: dflt
    });

  });