簡體   English   中英

如何使用 python 檢查 JSON 數據中是否存在數據庫中的逗號分隔值

[英]how to check whether the comma-separated value in the database is present in JSON data or not using python

我只需要根據表格中逗號分隔的 e_code 檢查 JSON 數據。 如何僅過濾數據庫中用戶 e_codes 可用的數據:

id         email          age      e_codes
1.         abc@gmail       19     123456,234567,345678
2.         xyz@gmail       31     234567,345678,456789

這是我的 JSON 數據

[
  {
    "ct": 1,
    "e_code": 123456,
  },
  {
    "ct": 2,
    "e_code": 234567,
  },
{
    "ct": 3,
    "e_code": 345678,
},
{
    "ct": 4,
    "e_code": 456789,
  },
{
    "ct": 5,
    "e_code": 456710,
  }
]

如果效率不是問題,您可以遍歷表,使用case['e_codes'].split(',')將值拆分為列表,然后,對於每個代碼循環,通過 JSON 查看它是否當下。 如果您的數據 JSON 或值的數量很長,這可能會有點低效。

最好先創建一個查找字典,其中代碼是鍵:

lookup={}
for e in my_json:
    lookup[e['e_code']] = 1

然后,您可以檢查表中有多少代碼實際上在 JSON 中:

## Let's assume that the "e_codes" cell of the 
## current line is data['e_codes'][i], where i is the line number

for i in lines:
    match = [0,0]
    for code in data['e_codes'][i].split(','):
        try:
            match[0]+=lookup[code]
            match[1]+=1
        except:
            match[1]+=1

    if match[1]>0: share_present=match[0]/match[1]

對於每種情況,您都會得到一個share_present ,如果所有代碼都出現在 JSON 中,則該值為 1.0,如果它們都沒有出現,則為 0.0,並且介於兩者之間的某個值表示存在的代碼的份額。 根據保留案例的閾值,您可以根據此值將過濾器設置為TrueFalse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM