簡體   English   中英

無法使用python讀取json文件

[英]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參數,該參數應該是以下任意一個:

arwrbwb

在工作目錄中有文件test.json ,這對我test.json

Test.json

{
  "foo": 1,
  "bar": 2,
  "baz": 3
}

Python腳本:

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.

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