json值转换为javascript

svdrlsy4  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(343)

这个问题在这里已经有答案了

如何访问和处理嵌套对象、数组或json(27个答案)
两年前关门了。
最近刚开始学习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}';
8dtrkrch

8dtrkrch1#

你需要分析 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
    });

  });

相关问题