Go vs PHP for short JSON-retrieving code

rodiongork

Rodion Gorkovenko

Posted on January 17, 2020

Go vs PHP for short JSON-retrieving code

I found this nice tutorial on retrieving data about recent earthquakes (from US gov service) - it nicely prints the place and magniuted of every event! Thanks to Christopher (@cskonopka )!

Example uses Go - and I'm currently studying this language. It seems, however, that for simple JSON retrieval/parsing task compiled languages are not excellent. I'm from Java world myself and it is always weird for me to create special class or structure repeating the expected JSON.

I feel Python or PHP may give easier code. So let's try for comparison (I choose PHP as it's syntactically closer to Go). I promise to find did struct-less approach in Go too :)

Let's code!

Firstly - create url by glueing the service address and date parameters:

$url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson";

$today = date('Y-m-d');
$yesterday = date('Y-m-d', time() - 24 * 60 * 60);

$fullUrl = "$url&starttime=$yesterday&endtime=$today";

Second step - fetch data, check for error and parse json:

$data = file_get_contents($fullUrl);

if ($data === false) {
    echo "Error retrieving json\n";
    exit(1);
}

$json = json_decode($data);

Third and last - let's print places and magnitudes of events!

foreach ($json->features as $record) {
    $prop = $record->properties;
    echo "{$prop->place} {$prop->mag}\n";
}

Analysis

So the code has much similarity between PHP and Go, but we get some leisure due to:

  • ready functions to perform HTTP request and parse JSON
  • fact that scripting language creates structs from JSON "on the fly"

The last is quite nice feature to me, as I mentioned, working in backend services with Java and similar compiled languages, I always felt it is painful rewriting and rebuilding files in several projects when some JSON response format is changed (this is especially true if some strictly-thinking colleague makes unmarshaller break upon new/unknown attributes).

However, as I said, I'm going now to try and see for struct-less approach in Go (brief googling hints there are ways). Hope to post this separately when I build example.

Thanks for reading that far :)

💖 💪 🙅 🚩
rodiongork
Rodion Gorkovenko

Posted on January 17, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related