簡體   English   中英

如何使用python從一個大的json文件中找出特定的鍵值對

[英]How to find out specific key-value pair from a big json file using python

我有一個很大的 json 文件,其中有多個 url。 格式是這樣的:

"url": "https://api/v1/test/fhfh"

我想從中創建 csv 文件,該文件將僅包含以 https://api 開頭的網址

我怎樣才能以最有效的方式做到這一點?

你可以試試這個方法。

json.json

如果你有多個 url 的大 json。

[
  {"url": "https://api/v1/test/fhfh1"},
  {"url": "https://api/v1/test/fhfh2"},
  {"url": "api/v1/test/fhfh"}
]

代碼

import json
import pandas as pd

with open('json.json', 'r') as f: # read json file
    data = json.loads(f.read())
    
case_list = [] # empty list
length_data = len(data)
n = 0
while n < length_data:
    if "https://api" in data[n]["url"]: # if https found then will append to case_list
        case_list.append(data[n])
    if n == length_data - 1:
        break
    n +=1

with open('case_list.json', 'w') as outfile: # write updated required json
     json.dump(case_list, outfile, indent=2, ensure_ascii=False)
df = pd.read_json ("case_list.json") 

df.to_csv ("case_list.csv", index = None) # change json to csv file.

輸出

print(df)
                         url
0  https://api/v1/test/fhfh1
1  https://api/v1/test/fhfh2

暫無
暫無

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

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