Quantcast
Channel: Converting JSON to .csv - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Sobrique for Converting JSON to .csv

$
0
0

JSON is a more detailed data format than CSV - it allows for more complex data structures. Inevitably if you do this, you 'lose detail'.

If you want to fetch it automatically - that's doable, but I've skipped it because 'doing'https URLs is slightly more complicated.

So assuming you've downloaded your file, here's a possible solution in Perl (You've already got one for Python - both are very powerful scripting languages, but can pretty much cover the same ground - so it's as much a matter of taste as to which you use).

#!/usr/bin/perluse strict;use warnings;use JSON;my $file = 'players.json';open( my $input, "<", $file ) or die $!;my $json_data = decode_json(    do { local $/; <$input> });foreach my $player_id ( keys %{$json_data} ) {    foreach my $fixture (        @{ $json_data->{$player_id}->{fixture_history}->{all} } )    {        print join( ",",            $player_id, $json_data->{$player_id}->{web_name},            @{$fixture}, "\n", );    }}

Hopefully you can see what's going on here - you load the file $input, and decode_json to create a data structure.

This data structure is a nested hash (perl's term for the type of data structure). hashes are key-value pairs.

So we extract the keys from this hash - which is the ID number right at the beginning of each entry.

Then we loop through each of them - extracting the the fixture_history array. And for each element in that array, we print the player ID, their web_name and then the data from fixture_history.

This gives output like:

1,Szczesny,10 Feb 19:45,25,LEI(H) 2-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2413,52,0,1,Szczesny,21 Feb 15:00,26,CRY(A) 2-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2805,52,0,1,Szczesny,01 Mar 14:05,27,EVE(H) 2-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1862,52,0,1,Szczesny,04 Mar 19:45,28,QPR(A) 2-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1248,52,0,1,Szczesny,14 Mar 15:00,29,WHU(H) 3-0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1897,52,0, 

Does this make sense?


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>