Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
(maybe) JSON to CSV
#11
(Oct-03-2017, 09:57 PM)nilamo Wrote: Why do you keep bringing up the csv module? 
My understanding is that OP wants to convert json to csv file.

Yes, you can look at CSV module and its DictWriter. That is in case my understanding is correct.
Reply
#12
nilamo you are correct, eventually I am going to write it to a csv file. I thought it would be easier as a proof of concept to just print it to the screen first instead of having to keep reopening a file.

I am having trouble with this code...
for dicts in data:
    first = True
    for key in dicts:
        if not first:
            print(", ", end="")
        first = False
        print(dicts[key], end="")
    print()
It is suggesting an unexpected indent at the last print.
Reply
#13
I don't see problem with the indentation. Could you post full traceback that you get, enclosed in error tags?
Also, check how you can iterate efficiently over key, values and items of a dict using keys(), values() and items() methods
https://docs.python.org/3/tutorial/datas...ctionaries
However, if you want to print all values, separated by comma, you can use str.join() method

>>> d={1:'one', 2:'two'}
>>> ','.join(d.values())
'one,two'
>>> 
Note that dict is unordered and you cannot be certain of the order in which each dict will be printed - both in your implementation and when using join. That is certain for versions up to python3.5. In CPython 3.6+ dict preserve the order of insertion, but this is still considered an implementation detail and one should not relied upon. https://docs.python.org/3.6/whatsnew/3.6...ementation
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020