簡體   English   中英

如何通過返回帶有所需參數的 json

[英]How to pass return the json with required parameters

我在下面有一個示例 Json。 作為回報,如果值匹配則只有一些參數。

  • 樣品 json 下面有 2 個文件

  • 我們是否需要創建單獨的 json 或列表和 append 或者我們只能將參數傳遞出去

  • 在示例 json 中,我正在搜索的值也可能會發生變化,也可能出現在另一個文檔中

    j = { "hits": [{ "_index": "dataproductall", "_type": "test", "_id": "3", "_score": 1.0, "_source": { "name": "Marketing 101", "room": "E4", "professor": { "name": "William Smith", "department": "finance", "facutly_type": "part-time", "email": "wills@onuni.com" }, "students_enrolled": 18, "course_publish_date": "2015-06-21", "course_description": "Mkt 101 is a course from the business school on the introduction to marketing that teaches students the fundamentals of market analysis, customer retention and online advertisements" } }, { "_index": "dataproductall", "_type": "test", "_id": "1", "_score": 1.0, "_source": { "id": "Accounting 101", "dataproduct": "E3", "professor": { "name": "Thomas Baszo", "department": "finance", "facutly_type": "part-time", "email": "baszot@onuni.com" }, "students_enrolled": 27, "course_publish_date": "2015-01-19", "course_description": "Act 101 is a course from the business school on the introduction to accounting that teaches students how to read and compose basic financial statements" } } ] }

我只需要返回必需的參數

如果 j['professor']['name'] = 'William Smith'

預期 output

然后只有下面的參數必須通過

"professor": {
                    "name": "William Smith",
                    "department": "finance",
                    "facutly_type": "part-time",
                    "email": "wills@onuni.com"
                }
     

遍歷命中並在名稱字段中搜索字符串。

僅提取 json 文檔中的professor部分並返回如下

name = #Prof. name you are searching for

for item in j["hits"]:
    if item['_source']['professor']['name'] == name:
        response = item['_source']['professor']
    break
return {"professor":response}

命中是整數,因此您不能只嘗試獲取

#Wrong
if j['professor']['name']
#Right
if j[integer]['professor']['name'] 

所以這將完成這項工作:

for hit in j['hits']:
    if hit["_source"]['professor']['name'] == 'William Smith':
        return(json.dumps({"professor":hit["_source"]["professor"]}, sort_keys=True, indent=4))

將導致:

{
    "professor": {
        "department": "finance",
        "email": "wills@onuni.com",
        "facutly_type": "part-time",
        "name": "William Smith"
    }
}

暫無
暫無

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

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