How to merge two json files that essentially load into a shape file (geojson)

55 views Asked by At

I have two json files one for England, the other for Scotland. I tried combining both and loading them as a shape file however geopandas only recognises one over the other. Is there a way to combine polygons of both json files?

Solution is below:

import pandas as pd 
import geopandas as gpd

file_list = ['topo_eer England.json','topo_eer Scotland.json']
dfs = [] # an empty list to store the data frames
for file in file_list:
 data = pd.read_json(file, lines=True) # read data frame from json file
 dfs.append(data) # append the data frame to the list

temp = pd.concat(dfs, ignore_index=True) # concatenate all the data frames in the list.
temp.to_json('temp.json', orient='records', lines=True)
df = gpd.read_file("temp.json")
df.plot()

Output (Only returns England..):

enter image description here

1

There are 1 answers

0
Ratislaus On

Assuming that you really need to combine the two files into one (and to be able to plot a data frame built from that file), you could read both JSON files as geo data frames, then concatenate them with pandas.concat, save the concatenated data frame to a new JSON file, read it to a special geo data frame, and finally plot that special geo data frame:

import pandas as pd 
import geopandas as gpd
import matplotlib.pyplot as plt

# read json files to geo data frames
sc_df = gpd.read_file("topo_eer_Scotland.json")
en_df = gpd.read_file("topo_eer_England.json")

# concatenate them using pandas
df = pd.concat([en_df, sc_df])
# save the concatenated data frame as a json file, if required
df.to_file("topo_eer_Scotland_and_England.json")
# read the resulting json file to a test geo data frame
test_df = gpd.read_file("topo_eer_Scotland_and_England.json")
# plot the test geo data frame to see how it works
test_df.plot()

plt.show()

The result:

enter image description here

But if you didn't care about having a combined JSON file, you could simply plot the respective geo data frames one by one, on the same matplotlib axes:

import pandas as pd 
import geopandas as gpd
import matplotlib.pyplot as plt

en_df = gpd.read_file("topo_eer_England.json")
sc_df = gpd.read_file("topo_eer_Scotland.json")
fig, ax = plt.subplots()
en_df.plot(ax=ax, color='red')
sc_df.plot(ax=ax, color='blue')

plt.show()

In this way, it would be easy to use some nice colors to be able to differentiate between the two countries:

enter image description here