Saturday, December 28, 2024
Google search engine
HomeLanguagesPython | Pandas Series.to_json()

Python | Pandas Series.to_json()

Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.

Pandas Series.to_json() function is used to convert the object to a JSON string. Also note that NaN’s and None will be converted to null and datetime objects will be converted to UNIX timestamps.

Syntax: Series.to_json(path_or_buf=None, orient=None, date_format=None, double_precision=10, force_ascii=True, date_unit=’ms’, default_handler=None, lines=False, compression=’infer’, index=True)

Parameter :
path_or_buf : File path or object. If not specified, the result is returned as a string.
orient : Indication of expected JSON string format.
date_format : None, ‘epoch’, ‘iso’}
double_precision : The number of decimal places to use when encoding floating point values.
force_ascii : Force encoded string to be ASCII.
date_unit : string, default ‘ms’ (milliseconds)
default_handler : callable, default None
lines : bool, default False
compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}

Returns : Json string

Example #1: Use Series.to_json() function to convert the given series object to JSON string.




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])
  
# Create the Datetime Index
didx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W'
                     periods = 6, tz = 'Europe/Berlin'
  
# set the index
sr.index = didx
  
# Print the series
print(sr)


Output :

Now we will use Series.to_json() function to convert the given series object to JSON string.




# convert to JSON string
sr.to_json()


Output :

As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.

Example #2: Use Series.to_json() function to convert the given series object to JSON string.




# importing pandas as pd
import pandas as pd
  
# Creating the Series
sr = pd.Series([19.5, 16.8, 22.78, 20.124, 18.1002])
  
# Print the series
print(sr)


Output :

Now we will use Series.to_json() function to convert the given series object to JSON string.




# convert to JSON string
sr.to_json()


Output :

As we can see in the output, the Series.to_json() function has successfully converted the given series object to JSON string.

RELATED ARTICLES

Most Popular

Recent Comments