![](/img/trans.png)
[英]How do I read the first 100 lines of a json metadata file and write them to a smaller json file? [Python]
[英]How do I read a json file into python?
我是 JSON 和 Python 的新手,對此的任何幫助將不勝感激。
我讀過 json.loads 但很困惑
如何使用 json.loads 將文件讀入 Python?
以下是我的 JSON 文件格式:
{
"header": {
"platform":"atm"
"version":"2.0"
}
"details":[
{
"abc":"3"
"def":"4"
},
{
"abc":"5"
"def":"6"
},
{
"abc":"7"
"def":"8"
}
]
}
我的要求是詳細讀取所有"abc"
"def"
的值並將其添加到這樣的新列表中[(1,2),(3,4),(5,6),(7,8)]
。 新列表將用於創建 spark 數據框。
打開文件,獲取文件句柄:
fh = open('thefile.json')
https://docs.python.org/2/library/functions.html#open
然后,將文件句柄傳遞給 json.load():(不要使用負載 - 那是用於字符串)
import json
data = json.load(fh)
https://docs.python.org/2/library/json.html#json.load
從那里,您可以輕松處理表示 json 編碼數據的 Python 字典。
new_list = [(detail['abc'], detail['def']) for detail in data['details']]
請注意,您的 JSON 格式也是錯誤的。 您將在許多地方需要逗號分隔符,但這不是問題。
我試圖盡可能地理解你的問題,但看起來它的格式很差。
首先,您的 json blob 不是有效的 json,它缺少很多逗號。 這可能是您正在尋找的:
{
"header": {
"platform": "atm",
"version": "2.0"
},
"details": [
{
"abc": "3",
"def": "4"
},
{
"abc": "5",
"def": "6"
},
{
"abc": "7",
"def": "8"
}
]
}
現在假設您嘗試在 python 中解析它,您將必須執行以下操作。
import json
json_blob = '{"header": {"platform": "atm","version": "2.0"},"details": [{"abc": "3","def": "4"},{"abc": "5","def": "6"},{"abc": "7","def": "8"}]}'
json_obj = json.loads(json_blob)
final_list = []
for single in json_obj['details']:
final_list.append((int(single['abc']), int(single['def'])))
print(final_list)
這將打印以下內容:[(3, 4), (5, 6), (7, 8)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.