1

In Python how to save the following JSON string into CSV file?

{
'1.txt': [], 
'2.txt': [], 
'5.txt': [], 
'4.txt': ['3.txt','6.txt'],
'7.txt': ['8.txt']
}

The important thing is that I want to save only numbers of those entries that have children, i.e. for the above example the result would be:

4
3
6
7
8

This is what I prepared so far, but I don't know how to check for nested elements:

    x = json.loads(data)

    f = csv.writer(open("test.csv", "wb+"))

    # Write CSV Header
    f.writerow(["number"])

    for x in x:
            f.writerow([x[...]])
2
  • Your example code does not match the intended output. Your CSV declares two header fields but intended output is line-by-line. Please clarify. Commented Mar 9, 2015 at 11:04
  • @dhke: Thanks, sorry, I edited the code. Commented Mar 9, 2015 at 11:43

2 Answers 2

1

Just check if the list is empty or not iterating of the items in the dict:

for k, v in d.items(): 
    if v: # will be False for any empty list
        print(k.split(".")[0])
        print([s.split(".")[0] for s in v])
7
['8']
4
['3', '6']

Depending on what output you want:

f = csv.writer(open("test.csv", "w")) 

# Write CSV Header
f.writerow(["name", "qty"])


for k, v in d.items(): # iteritems python2
    if v:
        f.writerow([k.split(".")[0]]+[s.split(".")[0] for s in v])

Which outputs:

name,qty
7,8
4,3,6

If you want all on separate lines:

with open("test.csv","w") as f:
    f.write("name\n")
    for k, v in d.items():
        if v:
            f.write("{}\n".format(k.split(".")[0]))
            f.write("\n".join([s.split(".")[0] for s in v])+"\n"

Output:

name
7
8
4
3
6

To use the csv module you would need to wrap the subelements in lists or some container:

with open("test.csv","w") as f:
    wr = csv.writer(f)
    wr.writerow(["name"])
    for k, v in d.items():
        if v:
            wr.writerow([k.split(".")[0]])
            wr.writerows([[s.split(".")[0]] for s in v])
Sign up to request clarification or add additional context in comments.

9 Comments

Thanks. You are right. I just need 1 column with numbers.
@KlausosKlausos, no worries, the writerows will put on on their own line.
After running your code, I received 3 columns with some strange numbers that do not coincide with my expectations. What might be the reason?
@KlausosKlausos, you know dicts have no order yes?
For instance, first line in CSV file is "1, 8, 5", however it is not correct.
|
0

This should be working:

data = {
    '1.txt': [], 
    '2.txt': [], 
    '5.txt': [], 
    '4.txt': ['3.txt','6.txt'],
    '7.txt': ['8.txt']
}
f = csv.writer(open("test.csv", "wb+"))
f.writerow(["name", "qty"])
for key, value in data.iteritems():
    if len(value) > 0:
        f.writerow([key, len(value)])

1 Comment

Side note: You can also use if not value, as bool([]) == False

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.