[英]Unable to read the json file using python
我正在嘗試讀取一個Mongodb輸入的json文件。 如果我可以將單個記錄編輯為有效的傑森,則可以。 但是當我嘗試讀取整個文件時,我無法做到。 它告訴我錯誤。
我已經完成了下面給出的基本代碼。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
# comment : Importing the json file to read;
database = "new 2.json"
data = json.loads(open(database).read())
# Comment : Variable Declaration;
# Comment : Display the json values;
for key,value in data.iteritems():
if 'patient_id' == key:
print("key: {0} | value: {1}".format(key, value))
if 'name' == key:
print("key: {0} | value: {1}".format(key, value))
if 'age' == key:
print("key: {0} | value: {1}".format(key, value))
if 'gender' == key:
print("key: {0} | value: {1}".format(key, value))
# for key,value in data.iteritems():
if 'address' == key:
print("key: {0} | value: {1}".format(key, value))
# if 'labRecords' == key:
# print("key: {0} | value: {1}".format(key, value))
我能夠打印一條記錄的數據,我已將其更正為正確的json文件。 但對於其他人,我需要修改所有記錄。 有什么辦法嗎???
看來您缺少第二個要open
參數,該參數應該是以下任意一個:
a
, r
, w
, rb
或wb
在工作目錄中有文件test.json
,這對我test.json
:
{
"foo": 1,
"bar": 2,
"baz": 3
}
import json
with open("test.json", "rb") as f:
data = json.load(f)
for key, value in data.items():
print(key, value)
foo 1
bar 2
baz 3
你可以試試看
import json
with open("json_data.json", mode='r', encoding='utf-8') as json_data:
data = json.load(json_data)
print(data)
json_data.json
{
"hello": 11,
"world": 22,
"json": 33
}
輸出
{'hello': 11, 'world': 22, 'json': 33}
確保您的json
格式數據正常。 並首先檢查您是否可以根據需要獲得輸出。 然后您就可以繼續進行進一步的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.