how to convert json to csv with python?

Chris Warrick kwpolska at gmail.com
Sat Jun 3 07:20:04 EDT 2017


On 3 June 2017 at 13:00, Ho Yeung Lee <davidbenny2000 at gmail.com> wrote:
> i use
> https://github.com/evidens/json2csv
>
> Error:
> Traceback (most recent call last):
>   File "json2csv.py", line 148, in <module>
>     loader.load(args.json_file)
>   File "json2csv.py", line 53, in load
>     self.process_each(json.load(json_file))
>   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 367, in decode
>     raise ValueError(errmsg("Extra data", s, end, len(s)))
> ValueError: Extra data: line 10 column 2 - line 50 column 2 (char 224 - 1179)
>
> sample file is
> {
>   "ip": "184.85.123.122",
>   "hostname": "No Hostname",
>   "city": "Cambridge",
>   "region": "Massachusetts",
>   "country": "US",
>   "loc": "42.3626,-71.0843",
>   "org": "AS20940 Akamai International B.V.",
>   "postal": "02142"
> },
> {
>   "ip": "203.185.0.32",
>   "hostname": "203185000032.ctinets.com",
>   "city": "Central District",
>   "region": "",
>   "country": "HK",
>   "loc": "22.2910,114.1500",
>   "org": "AS9269 HKBN AS10103"
> },
> [snip]

This is invalid JSON. You need to wrap all your dicts in a JSON array,
like this:

[
  {
     "ip": "…"
  },
  {
     "ip": "…"
  }
]

(just add [ and ] to the start and end of your file)

-- 
Chris Warrick <https://chriswarrick.com/>
PGP: 5EAAEA16



More information about the Python-list mailing list