简体   繁体   English

Json 键值与否?

[英]Json key has value or not?

i want to know json particular key has value or not我想知道json特定键是否有价值

please check my below json :请检查我下面的json:

[{"highest_education":"B.E ( Automobile Engineering )","occupation":"Job in Private Office","annual_income":""}]

in this json i want to check annual_income has value or not in PHP在这个json中,我想检查year_income在PHP中是否有价值

i dont want json_decode() and check every value it is not good solution我不想要 json_decode() 并检查每个值它不是好的解决方案

解码后首先解码json ,您将获得数组,然后使用条件检查特定值

 json_decode($myObj);

To check annual_income has value or not.检查 year_income 是否有价值。 You have to first convert your json data into array.您必须首先将 json 数据转换为数组。 like below code.像下面的代码。

$yourArray = json_encode($yourArray,true);

once your json will convert into array than u will check annual_income has value or not.一旦您的 json 将转换为数组,您将检查 year_income 是否有价值。

if(!empty($yourArray[0]['annual_income']) && $yourArray[0]['annual_income'] != ''){
  // Not empty
}

Well, I disagree that json_decode() has poor performance;好吧,我不同意json_decode()性能不佳; I'll show you the proof below.下面我给你看证明。

To achieve your task, you can use the following codes:要完成您的任务,您可以使用以下代码:

$json_string = '[{"highest_education":"B.E ( Automobile Engineering )","occupation":"Job in Private Office","annual_income":""}]';
$json_array = json_decode($json_string, true);
if(isset($json_array['annual_income']) && !empty($json_array['annual_income'])) {
    // value is not null
} else {
    // value is null or empty
}

There is no need to iterate through the JSON array at all.根本不需要遍历 JSON 数组。

Using PHP 7.1.16, I ran both methods for 1000 times, the performance difference between strpos() and json_decode() is not significant.使用 PHP 7.1.16,我将两种方法都运行了 1000 次, strpos()json_decode()之间的性能差异并不显着。

json_decode() used: 0.001691s
strpos() used: 0.00033s

Full test code is here: https://pastebin.com/ZcpjydfK , you can test it on your computer.完整的测试代码在这里: https : //pastebin.com/ZcpjydfK ,你可以在你的电脑上测试它。

On the other side, there is a problem using strpos() approach.另一方面,使用strpos()方法存在问题。 There is a chance that the JSON string is malformed, or space is added between the colon : , then your strpos() checking won't work.有可能 JSON 字符串格式错误,或者冒号:之间添加了空格,那么您的strpos()检查将不起作用。

it is not good way to json_decode() and check every key it is to much lengthy and make execution speed low这不是 json_decode() 并检查每个键的好方法,它太长并且执行速度低

i got the right answer我得到了正确的答案

$annual_income1='"annual_income":""';
$annual_income2='"annual_income":null';    
if(strpos($json,$annual_income1) !== false || strpos($json,$annual_income2) !== false){ 
echo "annual_income key is empty";
}

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

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