使用正则表达式遍历JavaScript中的json

时间:2019-01-10 10:27:35

标签: javascript json

我想遍历json并获取元素“ Data1”,“ Data2”,“ Data3”,“ Data4”的“ Value”。有没有不使用正则表达式来实现它的方法?我读过对json使用正则表达式不是一个好主意。

<script>
abc = {
"model": {
    "DataSection": {
        "Data1": {
            "Value": "1"
        },
        "Data2": {
            "Value": "2"
        },
        "Data3": {
            "Value": "3"
        },
        "Data4": {
            "Value": "4"
        }
    }
} 
}
</script>

2 个答案:

答案 0 :(得分:0)

是的,有:JSON.parse(string)

但是您给我们的不是JSON,而是javascript对象

abc = {
"model": {
    "DataSection": {
        "Data1": {
            "Value": "1"
        },
        "Data2": {
            "Value": "2"
        },
        "Data3": {
            "Value": "3"
        },
        "Data4": {
            "Value": "4"
        }
    }
} 
}

for (let data in abc.model.DataSection) {
  console.log(abc.model.DataSection[data].Value)
}


如果您真正拥有JSON,它将变成

abc = `{
"model": {
    "DataSection": {
        "Data1": {
            "Value": "1"
        },
        "Data2": {
            "Value": "2"
        },
        "Data3": {
            "Value": "3"
        },
        "Data4": {
            "Value": "4"
        }
    }
} 
}`
// abc is a string containing JSON

cde = JSON.parse(abc)
// cde is the object based on abc



for (let data in cde.model.DataSection) {
  console.log(cde.model.DataSection[data].Value)
}

答案 1 :(得分:0)

如果无需使用正则表达式就可以执行某些操作,则请执行。在这里,我创建一个数组并将所有值放入其中。

abc = {
  "model": {
    "DataSection": {
      "Data1": {
        "Value": "1"
      },
      "Data2": {
        "Value": "2"
      },
      "Data3": {
        "Value": "3"
      },
      "Data4": {
        "Value": "4"
      }
    }
  }
}

var array = []

$.each(abc.model.DataSection, function(index, value) {
  array.push(value.Value)
});

console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>