简体   繁体   English

在JSON中搜索数据-JavaScript

[英]Search for data in json - javascript

I have a json output as 我有一个json输出为

amt: "10.00"
email: "sam@gmail.com"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"

Literally Im trying to do this in javascript 从字面上看,我试图用javascript做到这一点

if(the json output has the key merchant_id)
{
//do something
}

How is it possible to find if a json output has a key like as I demonstrated above?Is it possible,Or is there any alternate method for it? 如何确定json输出是否具有如上所述的键?是否有可能,或者是否有其他替代方法?

Let's say you have JSON object like this: 假设您有这样的JSON对象:

var json = {
   amt: "10.00",
   email: "sam@gmail.com",
   merchant_id: "sam",
   mobileNo: "9874563210",
   orderID: "123456",
   passkey: "1234"
}

So now you have to use a loop. 所以现在您必须使用循环。 Eg 例如

for(var j in json) { // var j is the key in this loop
   if(j == 'merchant_id') {
      // do something
   }
}

You can just check the type of of the field. 您可以只检查字段的类型。

if (typeof json.property !== 'undefined') {
    //has property
}

If this is a multiline string like you wrote it, a simple way is: 如果这是您编写的多行字符串,则一种简单的方法是:

if(s.indexOf("\nmerchant_id: \"whatever\"\n")>-1) {
    // ...
}

But you can parse it of course, and that's the elegant way. 但是您当然可以解析它,这是一种优雅的方式。 With a json object, you can just refer to the field with a dot, like "obj.merchant_id". 使用json对象,您可以仅使用点来引用字段,例如“ obj.merchant_id”。

For example, try this: 例如,尝试以下操作:

var data = {
   amt: "10.00",
   email: "sam@gmail.com",
   merchant_id: "sam",
   mobileNo: "9874563210",
   orderID: "123456",
   passkey: "1234"
}

if(data.amt == 'something'){
   // do work
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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