We can easily create a pandas Series
from the JSON string in the previous example. The pandas read_json()
function can create a pandas Series
or pandas DataFrame
.
The following example code can be found in pd_json.py
of this book's code bundle:
import pandas as pd json_str = '{"country":"Netherlands","dma_code":"0","timezone":"Europe/Amsterdam","area_code":"0","ip":"46.19.37.108","asn":"AS196752","continent_code":"EU","isp":"Tilaa V.O.F.","longitude":5.75,"latitude":52.5,"country_code":"NL","country_code3":"NLD"}' data = pd.read_json(json_str, typ='series') print "Series ", data data["country"] = "Brazil" print "New Series ", data.to_json()
We can either specify a JSON string or the path of a JSON file. Call the read_json()
function to create a pandas Series
from the JSON string in the previous example:
data = pd.read_json(json_str, typ='series') print "Series ", data
In the resulting Series
, the keys are ordered in alphabetical order:
Series area_code 0 asn AS196752 continent_code EU country Netherlands country_code NL country_code3 NLD dma_code 0 ip 46.19.37.108 ispTilaa V.O.F. latitude 52.5 longitude 5.75 timezone Europe/Amsterdam dtype: object
Change the country
value again and convert the pandas Series
to a JSON string with the to_json()
method:
data["country"] = "Brazil" print "New Series ", data.to_json()
In the new JSON string, the key order is preserved, but we also have a different country
value:
New Series {"area_code":"0","asn":"AS196752","continent_code":"EU","country":"Brazil","country_code":"NL","country_code3":"NLD","dma_code":"0","ip":"46.19.37.108","isp":"Tilaa V.O.F.","latitude":52.5,"longitude":5.75,"timezone":"Europe/Amsterdam"}
18.221.89.18