I have this JSON file:
[
{
id: "29",
name: "abc",
email: "def@school.edu",
data: "2016-05-03"
},
{
id: "17",
name: "ghi",
email: "jkl@school.edu",
data: "2016-05-12"
},
{
id: "12",
name: "qwe",
email: "cde@school.edu",
data: "2016-04-11"
}
]
I wrote this script:
with open('C:/Users/L30607/Desktop/FYP/FourthMay-AllStudents-stackoverflow.json') as json_data:
d = json.load(json_data)
json_data.close()
pprint(d)
How do I parse the file and extract the array?
I want to get:
d = [{id: "29",name: "abc",email: "def@school.edu",data: "2016-05-03"},{id: "17",name: "ghi",email: "jkl@school.edu",data: "2016-05-12"},{id: "12",name: "qwe",email: "cde@school.edu",data: "2016-04-11"}]
Your JSON is not formatted properly. I put validated it in https://jsonformatter.curiousconcept.com/ and it shows that your keys are not wrapped in quotes. This is what it should be:
[
{
"id":"29",
"name":"abc",
"email":"def@school.edu",
"data":"2016-05-03"
},
{
"id":"17",
"name":"ghi",
"email":"jkl@school.edu",
"data":"2016-05-12"
},
{
"id":"12",
"name":"qwe",
"email":"cde@school.edu",
"data":"2016-04-11"
}
]
I re-ran your code and it worked well.
This is the error:
Traceback (most recent call last): File "C:/Users/L30607/PycharmProjects/untitled1/333.py", line 36, in d = json.load(json_data) File "C:\\Python27\\lib\\json__init__.py", line 291, in load **kw) File "C:\\Python27\\lib\\json__init__.py", line 339, in loads return _default_decoder.decode(s) File "C:\\Python27\\lib\\json\\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\\Python27\\lib\\json\\decoder.py", line 380, in raw_decode obj, end = self.scan_once(s, idx) ValueError: Expecting property name: line 3 column 1 (char 4)
Always validate your json from http://jsonlint.com/ if you get any errors. In your case you are not giving Keys as string.
Your json should be like :
[{
"id": "29",
"name": "abc",
"email": "def@school.edu",
"data": "2016-05-03"
}, {
"id": "17",
"name": "ghi",
"email": "jkl@school.edu",
"data": "2016-05-12"
}, {
"id": "12",
"name": "qwe",
"email": "cde@school.edu",
"data": "2016-04-11"
}]
String should be inside quotes. Then only it becomes as valid JSON. You can validate your JSON : Validate JSON
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.