I have a json output as
amt: "10.00"
email: "sam@gmail.com"
merchant_id: "sam"
mobileNo: "9874563210"
orderID: "123456"
passkey: "1234"
Literally Im trying to do this in 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?
Let's say you have JSON object like this:
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".
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
}
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.