Posts: 14
Threads: 2
Joined: Nov 2019
using below script i am getting error at multilevel. When i use get for x["salary"][0]["SID"] i get error in script
import json
import csv
with open('/local/dummy.json') as f:
json_data = json.load(f, strict=False)
with open('/local/application.csv', 'w') as outfile:
csv_write = csv.writer(outfile)
csv_write.writerow(["id", "SID", "Type", "ttt"])
for x in json_data["dummy"]:
csv_write.writerow([x["id"],
x["name"],
x.get("name",'None'),
x["salary"][0]["SID"]])
Posts: 14
Threads: 2
Joined: Nov 2019
i have object inside array and when i am trying to fecth details i am getting index error
row_array.append(json_d["axe"][0]["name"]) error; -
IndexError: list index out of range
Posts: 8,168
Threads: 160
Joined: Sep 2016
Nov-27-2019, 09:03 AM
(This post was last modified: Nov-27-2019, 09:04 AM by buran.)
Both JSON files/strings that you post in post#1 and in post #10 are not valid json as you can check https://jsonlint.com/
Posts: 14
Threads: 2
Joined: Nov 2019
Json file: -
{
"id": 1,
"name": "Auto",
"architecture": {
"axe": [
"j",
"y",
"r",
"t",
"x"
],
"p": [
"Vir",
"M"
]
},
"LL": [
{
"id": 10,
"name": "A",
"xx": "D",
"bb": "aa",
"yy": "S"
]
}
}
python script used:-
import sys
import json
import csv
reload(sys)
sys.setdefaultencoding('utf8')
with open('a.json','r') as f:
json_data=json.load(f,strict=False)
with open('a.csv','w') as outfile:
csv_write=csv.writer(outfile,quoting=csv.QUOTE_ALL)
csv_write.writerow(["id","xx"])
for json_d in json_data["a"]:
row_array = []
try:
row_array.append(json_d["Id"])
except KeyError:
row_array.append('')
try:
row_array.append(json_d["LL"][0]["xx"])
except (KeyError,TypeError):
row_array.append('')
except TypeError:
row_array.append('')
csv_write.writerow(row_array)
outfile.close() i am getting error -IndexError: list index out of range on command -row_array.append(json_d["LL"][0]["xx"])
Posts: 8,168
Threads: 160
Joined: Sep 2016
Nov-27-2019, 09:27 AM
(This post was last modified: Nov-27-2019, 09:27 AM by buran.)
This is NOT valid JSON!!!!
(Nov-27-2019, 09:12 AM)rajrishi990 Wrote: Json file: -
{
"id": 1,
"name": "Auto",
"architecture": {
"axe": [
"j",
"y",
"r",
"t",
"x"
],
"p": [
"Vir",
"M"
]
},
"LL": [
{
"id": 10,
"name": "A",
"xx": "D",
"bb": "aa",
"yy": "S"
]
}
}
Posts: 14
Threads: 2
Joined: Nov 2019
Nov-27-2019, 09:28 AM
(This post was last modified: Nov-27-2019, 09:33 AM by buran.)
valid json: -
Output: {
"a": [{
"id": 1,
"name": "Auto",
"architecture": {
"axe": [
"j",
"y",
"r",
"t",
"x"
],
"p": [
"Vir",
"M"
]
},
"LL": [{
"id": 10,
"name": "A",
"xx": "D",
"bb": "aa",
"yy": "S"
}]
}]
}
Posts: 2,128
Threads: 11
Joined: May 2017
This:
import json
import csv
from pathlib import Path
DESKTOP = Path.home() / "Desktop"
with open(DESKTOP / "my_data.json") as fd:
json_data = json.load(fd)
# print(list(json_data['a'][0]))
with open(DESKTOP / "a.csv", "w") as outfile:
writer = csv.writer(outfile, quoting=csv.QUOTE_ALL)
header = ["id", "xx"]
print("Writing header:", header)
writer.writerow(header)
for json_d in json_data["a"]:
row_array = []
row_array.append(json_d.get("id") or "NO ID")
try:
row_array.append(json_d["LL"][0]["xx"])
except (KeyError, TypeError):
row_array.append("NO XX")
print("Writing row", row_array)
writer.writerow(row_array)
#with open(DESKTOP / "a.csv", "rb") as outfile:
# print(outfile.read()) Should parse this:
{
"a": [{
"id": 1,
"name": "Auto",
"architecture": {
"axe": [
"j",
"y",
"r",
"t",
"x"
],
"p": [
"Vir",
"M"
]
},
"LL": [{
"id": 10,
"name": "A",
"xx": "D",
"bb": "aa",
"yy": "S"
}]
}]
} I get some unexpected \r, but don't have time to investigate.
Choose next time real data and this garbage, where no one knows what is what.
I tested this on windows. I put the files in a different path.
Output: Writing header: ['id', 'xx']
Writing row [1, 'D']
File content:
Output: "id","xx"
"1","D"
Posts: 8,168
Threads: 160
Joined: Sep 2016
Nov-27-2019, 12:04 PM
(This post was last modified: Nov-27-2019, 12:04 PM by buran.)
(Nov-27-2019, 11:56 AM)DeaD_EyE Wrote: I get some unexpected \r, but don't have time to investigate. (Nov-27-2019, 11:56 AM)DeaD_EyE Wrote: I tested this on windows.
When using csv module pass newline='' as argument to open. It's stated in the docs:
Quote:If csvfile is a file object, it should be opened with newline=''. 1
This will resolve the extra blank lines when on Windows. On Linux it will work as expected without that argument, but no harm when it's there.
Here is the relevant docs
https://docs.python.org/3/library/csv.html#id3
https://docs.python.org/3/library/functi...-parameter
|