英文:
Check if column exists in Nested JSON
问题
以下是我的示例JSON:
{
"_id": {
"$oid": "1564t8re13e4ter86"
},
"object": {
"shop": "shop1",
"domain": "Divers",
"sell": [
{
"location": {
"zipCode": "58000",
"city": "NEVERS"
},
"properties": {
"description": "ddddd!!!!",
"id": "f1re67897116fre87"
},
"employee": [
{
"name": "employee1",
"id": "245975"
},
{
"name": "employee2",
"id": "458624"
}
],
"customer": {
"name": "Customer1",
"custid": "test_réf"
},
"preference": "talking"
}
]
}
}
在上述示例中,我想知道 $.object.sell.preference 是否存在,因为在大多数情况下它是不存在的,这导致了失败。
另外,如果在使用 readcontext.read($...) 时能够设置选项以返回 null 或空值,我会很满意。
谢谢!
英文:
Below is my sample JSON
{
"_id":{
"$oid":"1564t8re13e4ter86"
},
"object":{
"shop":"shop1",
"domain":"Divers",
"sell":[
{
"location":{
"zipCode":"58000",
"city":"NEVERS"
},
"properties":{
"description":"ddddd!!!!",
"id":"f1re67897116fre87"
},
"employee":[
{
"name":"employee1",
"id":"245975"
},
{
"name":"employee2",
"id":"458624"
}
],
"customer":{
"name":"Customer1",
"custid":"test_réf"
}
"preference":"talking"
}
]
}
}
In the above sample i would like to know if this particular column exists in the $.object.sell.preference exists , as in most cases it is not existing which is leading to failure.
Also i am good if there is any option i can set to get null or blank as return when using readcontext.read($...)
Thanks in Advance
Regards
答案1
得分: 3
是的,可以使用jsonObject.has()
方法进行检查。
假设您有一个名为response
的变量,其中包含完整的JSON数据。
您可以像这样进行操作:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONObject("object").getJSONArray("sell");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("preference")) {
// 存在
} else {
// 不存在
}
}
英文:
NOTE: I'm referring in java
Yes, it is possible to check using jsonObject.has() method.
Suppose you have response variable in which you have full JSON
You can proceed it like this
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONObject("object").getJSONArray("sell");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("preference")) {
// Exist
} else {
//Not Exist
}
}
答案2
得分: 1
尝试:
bool(json['object']['sell'][0]["preference"])
如果为空则返回false,反之亦然
英文:
try:
bool(json['object']['sell'][0]["preference"])
it will return false if empty and vice versa
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论