简体   繁体   中英

How do I access these JSON values?

I am trying to access JSON values. This is the JSON object:

       {
   "attrs": {
      "width": 1728,
      "height": 787,
      "dragabble": true
   },
   "className": "Stage",
   "children": [
      {
         "attrs": {},
         "className": "Layer",
         "children": [
            {
               "attrs": {
                  "stroke": "green",
                  "strokeWidth": "5",
                  "points": [
                     348,564.125
                  ]
               },
               "className": "Line"
            }
         ]
      }
   ]
}

And I am trying to use these values, like points, here:

socket.on("canvas-data", function(data){
    var interval = setInterval(function(){
      if(isDrawing) return;
      setIsDrawing(true);
      clearInterval(interval);
      var obj = JSON.parse(data);
      setStageData(obj);
      var layer = new Konva.Layer();
      var lines = new Konva.Line(
      {
        stroke: stageData.stroke,
        strokeWidth: stageData.strokeWidth,
        points: stageData.points
      })
    layer.add(lines);

    stageEl.current.add(layer);

    }, 200)
  })

data is the JSON string, I tried to parse data into obj , set my stageData to obj and then set the corresponding JSON attributes to the values like stroke , strokeWidth and points . This doesn't work however, they're undefined. How do I access them?

(I also tried skipping the step where I set my stageData to obj , and just use obj.stroke instead of stageData.stroke etc.)

You can just skip using setStageData() and use the parsed object directly if you wish, or just name the parsed object stageData by default. In any case, when you have nested objects and values in an Object, you access them by using the correct index, in your case, it would look this way:

socket.on("canvas-data", function(data) {
  var interval = setInterval(function() {
    if (isDrawing) return;
    setIsDrawing(true);
    clearInterval(interval);
    var stageData = JSON.parse(data);
    var layer = new Konva.Layer();
    var lines = new Konva.Line(
      {
        stroke: stageData.children[0].children[0].attrs.stroke,
        strokeWidth: stageData.children[0].children[0].attrs.strokeWidth,
        points: stageData.children[0].children[0].attrs.points
      });
    layer.add(lines);

    stageEl.current.add(layer);

  }, 200);
})

Doesn't look very nice, but it works. You can always use this app called JSON Path list, which shows you all the possible paths and their values in a JSON object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM