简体   繁体   English

无法使用python读取json文件

[英]Unable to read the json file using python

i am trying to read a json file that is the input for Mongodb. 我正在尝试读取一个Mongodb输入的json文件。 if i can edit a single record as a valid jason i am able to do so. 如果我可以将单个记录编辑为有效的杰森,则可以。 but when i am trying to read the entire file, i am not able to do it. 但是当我尝试读取整个文件时,我无法做到。 it shows me error. 它告诉我错误。

Error message 错误信息

I have done a base code like given below. 我已经完成了下面给出的基本代码。

#!/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))

i am able to print the data for a single record, that i have corrected into a proper json file. 我能够打印一条记录的数据,我已将其更正为正确的json文件。 but for the others i need to modify all the records. 但对于其他人,我需要修改所有记录。 is there any way to do it??? 有什么办法吗???

It looks like you are missing the second parameter to open which should be one of either: 看来您缺少第二个要open参数,该参数应该是以下任意一个:

a , r , w , rb , or wb arwrbwb

With the file test.json in the working directory, this works for me: 在工作目录中有文件test.json ,这对我test.json

Test.json Test.json

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

Python script: Python脚本:

import json

with open("test.json", "rb") as f:
    data = json.load(f)


for key, value in data.items():
    print(key, value)

Output: 输出:

foo 1
bar 2
baz 3

You can try this. 你可以试试看

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 json_data.json

 {
  "hello": 11,
  "world": 22,
  "json": 33
}

output 输出

{'hello': 11, 'world': 22, 'json': 33}

make sure your json format data is ok. 确保您的json格式数据正常。 and check first you get the output as you want. 并首先检查您是否可以根据需要获得输出。 and than you can proceed your further work. 然后您就可以继续进行进一步的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM