### Read JSON-stat Dataset from UK ONS API (Python) Source: https://github.com/predicador37/pyjstat/blob/master/README.rst Example of reading a JSON-stat dataset directly from the UK ONS API, demonstrating URL construction with parameters and an API key. Requires pyjstat. ```python from pyjstat import pyjstat EXAMPLE_URL = 'http://web.ons.gov.uk/ons/api/data/dataset/DC1104EW.json?'\ 'context=Census&jsontype=json-stat&apikey=yourapikey&'\ 'geog=2011HTWARDH&diff=&totals=false&'\ 'dm/2011HTWARDH=E12000007' dataset = pyjstat.Dataset.read(EXAMPLE_URL) df = dataset.write('dataframe') print(df) ``` -------------------------------- ### Request Data from URL Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Sends an HTTP GET request to a specified URL to retrieve data in JSON format. It includes an option to verify SSL certificates. The function returns the deserialized JSON response. It can raise HTTPError, InvalidURL, or other generic exceptions. ```python pyjstat.request(path, verify=True) ``` -------------------------------- ### Get data value by query - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves a specific data value from a `pyjstat.Dataset` by providing a query, which is a list of dictionaries specifying the desired dimension and category. This method facilitates precise data extraction based on dimensional criteria. ```python from pyjstat import Dataset # Assuming 'my_dataset' is an instance of pyjstat.Dataset query = [ {'dimension': 'country', 'category': 'canada'}, {'dimension': 'year', 'category': '2020'} ] value = my_dataset.get_value(query) print(f"Data value for query: {value}") ``` -------------------------------- ### Get element from collection - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves a specific element from a `pyjstat.Collection` object. The `get` method can return the element as either a JSON-stat string or a list of pandas DataFrames, depending on the specified output format. ```python from pyjstat import Collection # Assuming 'my_collection' is an instance of pyjstat.Collection # Get the first element as a DataFrame list first_element_df = my_collection.get(0, output='dataframe_list') # Get the second element as JSON-stat second_element_json = my_collection.get(1, output='jsonstat') ``` -------------------------------- ### Get Values from JSON-stat Data Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves the dataset values from a JSON-stat formatted input. It takes the dataset dictionary and an optional value column name (defaulting to 'value'). The function returns a list containing the dataset's values. ```python pyjstat.get_values(js_dict, value='value') ``` -------------------------------- ### Get data value by numeric index - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Extracts a data value from a `pyjstat.Dataset` using its numeric index. This method is useful when the position of the data point is known, providing a direct way to access individual values. ```python from pyjstat import Dataset # Assuming 'my_dataset' is an instance of pyjstat.Dataset # Get the value at index 5 index = 5 value = my_dataset.get_value_by_index(index) print(f"Data value at index {index}: {value}") ``` -------------------------------- ### Get Specific Value from JSON-stat Dataset (Python) Source: https://github.com/predicador37/pyjstat/blob/master/README.rst Shows how to extract a specific data value from a JSON-stat dataset based on a query. This function mimics the behavior of the JSON-stat Javascript sample. Requires pyjstat. ```python from pyjstat import pyjstat EXAMPLE_URL = 'http://json-stat.org/samples/oecd.json' query = [{'concept': 'UNR'}, {'area': 'US'}, {'year': '2010'}] dataset = pyjstat.Dataset.read(EXAMPLE_URL) print(dataset.get_value(query)) ``` -------------------------------- ### Get dimension index by name and value - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html The `get_dimension_index` method in `pyjstat.Dataset` retrieves the numeric index of a category within a specific dimension. It takes the dimension's ID string and the category's ID string as input, returning the corresponding index. ```python from pyjstat import Dataset # Assuming 'my_dataset' is an instance of pyjstat.Dataset # Get the index for category 'canada' in the dimension 'country' dimension_name = 'country' category_value = 'canada' index = my_dataset.get_dimension_index(dimension_name, category_value) print(f"Index for '{category_value}' in '{dimension_name}': {index}") ``` -------------------------------- ### Get Unique Values Preserving Order Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Returns a list containing only the unique values from an input list, while maintaining the original order of appearance. This function is useful for data cleaning and preparing lists for analysis. ```python pyjstat.uniquify(seq) ``` -------------------------------- ### Get dimension indices from query - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html The `get_dimension_indices` method allows converting a list of dictionaries, where each dictionary specifies a dimension and a category, into a list of numeric dimension indices. This is a utility function for accessing specific data points within a dataset. ```python from pyjstat import Dataset # Assuming 'my_dataset' is an instance of pyjstat.Dataset query = [ {'dimension': 'country', 'category': 'canada'}, {'dimension': 'year', 'category': '2020'} ] indices = my_dataset.get_dimension_indices(query) print(f"Dimension indices for query: {indices}") ``` -------------------------------- ### Get numeric value index from dimension indices - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Converts a list of dimension indices into a single numeric value index. This function is crucial for mapping dimensional selections to the flat structure of data values within the JSON-stat format. ```python from pyjstat import Dataset # Assuming 'my_dataset' is an instance of pyjstat.Dataset dimension_indices = [0, 2] # Example indices for dimensions value_index = my_dataset.get_value_index(dimension_indices) print(f"Numeric value index for {dimension_indices}: {value_index}") ``` -------------------------------- ### Get Dimension Label from JSON-stat Dictionary Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Fetches the label for a given dimension from a JSON-stat formatted dictionary. It accepts the dataset dictionary, the dimension name, and an optional input type ('dataset' by default). The function returns a pandas DataFrame containing label-based dimension data, aiding in understanding dimension categories. ```python pyjstat.get_dim_label(js_dict, dim, dim_input='dataset') ``` -------------------------------- ### Get Dimension Index from JSON-stat Dictionary Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves the index for a specified dimension from a dictionary containing JSON-stat data. It takes the dataset dictionary and the dimension name as input and returns a pandas DataFrame with the index-based dimension data. This function is useful for locating specific dimensions within the dataset. ```python pyjstat.get_dim_index(js_dict, dim) ``` -------------------------------- ### Get Dimensions from JSON-stat Data Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Extracts dimension names from JSON-stat formatted input data. Users can specify the naming convention for dimensions ('label' or 'id'). The function returns a list of pandas DataFrames, where each DataFrame contains category data for a dimension, and a list of dimension names. ```python pyjstat.get_dimensions(js_dict, naming) ``` -------------------------------- ### pyjstat.request Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Sends a request to a given URL to fetch JSON data. ```APIDOC ## pyjstat.request ### Description Send a request to a given URL accepting JSON format. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python try: data = pyjstat.request('https://example.com/data.json') except Exception as e: print(f"An error occurred: {e}") ``` ### Response #### Success Response (200) - **response** (object) - Deserialized JSON Python object. #### Response Example ```json { "example": "[Deserialized JSON object]" } ``` ### Error Handling - **HTTPError**: the HTTP error returned by the requested server. - **InvalidURL**: an invalid URL has been requested. - **Exception**: generic exception. ``` -------------------------------- ### Show Search Box - JavaScript Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/index.html This JavaScript snippet is used to display the search box on the documentation page. It is triggered by a specific event and is commonly found in web documentation frameworks like Sphinx. ```javascript $('#searchbox').show(0); ``` -------------------------------- ### pyjstat.Dataset Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Represents a JSON-stat dataset and provides methods for data retrieval and manipulation. ```APIDOC ## pyjstat.Dataset ### Description A class representing a JSONstat dataset. ### Methods #### `get_dimension_index(name, value)` **Description**: Get a dimension index from its name. Converts a dimension ID string and a category ID string into the numeric index of that category in that dimension. **Parameters**: - **name** (string) - ID string of the dimension. - **value** (string) - ID string of the category. **Returns**: Index of the category in the dimension (int). #### `get_dimension_indices(query)` **Description**: Get dimension indices. Converts a dimension/category list of dicts into a list of dimension indices. **Parameters**: - **query** (list) - Dimension/category list of dicts. **Returns**: List of dimensions' indices (list). #### `get_value(query)` **Description**: Get data value. Converts a dimension/category list of dicts into a data value in three steps. **Parameters**: - **query** (list) - List of dicts with the desired query. **Returns**: Numeric data value (float). #### `get_value_by_index(index)` **Description**: Convert a numeric value index into its data value. **Parameters**: - **index** (int) - Numeric value index. **Returns**: Numeric data value (float). #### `get_value_index(indices)` **Description**: Convert a list of dimension indices into a numeric value index. **Parameters**: - **indices** (list) - List of dimension’s indices. **Returns**: Numeric value index (int). #### `read(data, verify=True, **kwargs)` (classmethod) **Description**: Read data from URL, Dataframe, JSON string/file or OrderedDict. **Parameters**: - **data** - Can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. - **verify** - Whether to host’s SSL certificate. - **kwargs** - Optional arguments for to_json_stat(). **Returns**: An object of class Dataset populated with data. ``` -------------------------------- ### Import JSON-stat into pandas DataFrame - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Demonstrates how to load a JSON-stat file from a URL into a pandas DataFrame using pyjstat. This involves fetching the JSON data, parsing it, and then converting it into a DataFrame structure. Dependencies include `urllib2`, `json`, and `pyjstat`. ```python import urllib2 import json import pyjstat results = pyjstat.from_json_stat(json.load(urllib2.urlopen( 'http://json-stat.org/samples/oecd-canada.json'))) print results ``` -------------------------------- ### Read Data into Dimension Object (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Creates a Dimension object by reading data from various sources including URLs, pandas DataFrames, JSON strings/files, or OrderedDict. This is a class method for initializing a Dimension instance. ```python from pyjstat import Dimension # Example reading from a URL dimension_object = Dimension.read('http://example.com/data.json') # Example reading from a pandas DataFrame # import pandas as pd # df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) # dimension_object = Dimension.read(df) ``` -------------------------------- ### check_input Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Checks and validates the input naming parameter. ```APIDOC ## POST /check_input ### Description Check and validate input params, specifically the naming type. ### Method POST ### Endpoint /check_input ### Parameters #### Request Body - **naming** (string) - A string containing the naming type ('label' or 'id'). ### Request Example { "example": "{\"naming\": \"label\"}" } ### Response #### Success Response (200) - **message** (string) - Indicates successful validation. #### Error Response (400) - **error** (string) - "ValueError: if the parameter is not in the allowed list." #### Response Example { "example": "Validation successful." } ``` -------------------------------- ### Dataset.write Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Writes data from a Dataset object to JSONstat format or a Pandas DataFrame. ```APIDOC ## POST /Dataset.write ### Description Write data from a Dataset object to JSONstat or Pandas Dataframe. ### Method POST ### Endpoint /Dataset.write ### Parameters #### Query Parameters - **output** (string) - Optional - Can accept ‘jsonstat’ or ‘dataframe’. Defaults to ‘jsonstat’. - **naming** (string) - Optional - Dimension naming. Possible values: ‘label’ or ‘id’. Defaults to ‘label’. Ignored if output = ‘jsonstat’. - **value** (string) - Optional - Name of value column. Defaults to ‘value’. Ignored if output = ‘jsonstat’. ### Request Example { "example": "{\"output\": \"jsonstat\", \"naming\": \"label\", \"value\": \"value\"}" } ### Response #### Success Response (200) - **data** (string | DataFrame) - Serialized JSONstat or a Pandas Dataframe, depending on the ‘output’ parameter. #### Response Example { "example": "(JSONstat string or Pandas DataFrame representation)" } ``` -------------------------------- ### pyjstat.get_values Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves the values from input data, with an option to specify the value column name. ```APIDOC ## pyjstat.get_values ### Description Get values from input data. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming js_dict is a loaded JSON-stat object values_list = pyjstat.get_values(js_dict, value='value') ``` ### Response #### Success Response (200) - **values** (list) - List of dataset values. #### Response Example ```json { "example": [ 100, 150, 200 ] } ``` ``` -------------------------------- ### Read and Write JSON-stat Dataset to DataFrame (Python) Source: https://github.com/predicador37/pyjstat/blob/master/README.rst Demonstrates reading a JSON-stat dataset from a URL and converting it into a pandas DataFrame, and vice versa. Requires the pyjstat and pandas libraries. ```python from pyjstat import pyjstat EXAMPLE_URL = 'http://json-stat.org/samples/galicia.json' # read from json-stat dataset = pyjstat.Dataset.read(EXAMPLE_URL) # write to dataframe df = dataset.write('dataframe') print(df) # read from dataframe dataset_from_df = pyjstat.Dataset.read(df) # write to json-stat print(dataset_from_df.write()) ``` -------------------------------- ### pyjstat.Collection Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Represents a JSON-stat collection and provides methods for reading and writing data. ```APIDOC ## pyjstat.Collection ### Description A class representing a JSONstat collection. ### Methods #### `get(element)` **Description**: Get element from collection. **Parameters**: - **output** (string) - Can accept 'jsonstat' or 'dataframe_list'. **Returns**: Serialized JSONstat or a list of Pandas Dataframes, depending on the 'output' parameter. #### `read(data)` (classmethod) **Description**: Read data from URL or OrderedDict. **Parameters**: - **data** - Can be a URL pointing to a JSONstat file, a JSON string or an OrderedDict. **Returns**: An object of class Collection populated with data. #### `write(output='jsonstat')` **Description**: Write to JSON-stat or list of df. Writes data from a Collection object to JSONstat or list of Pandas Dataframes. **Parameters**: - **output** (string) - Can accept 'jsonstat' or 'dataframe_list'. **Returns**: Serialized JSONstat or a list of Pandas Dataframes, depending on the 'output' parameter. ``` -------------------------------- ### generate_df Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Helper method to decode JSON-stat dict into a Pandas DataFrame. ```APIDOC ## POST /generate_df ### Description Decode JSON-stat dict into pandas.DataFrame object. Helper method that should be called inside from_json_stat(). ### Method POST ### Endpoint /generate_df ### Parameters #### Request Body - **js_dict** (OrderedDict) - OrderedDict with data in JSON-stat format, previously deserialized into a Python object. - **naming** (string) - Dimension naming. Possible values: ‘label’ or ‘id.’ - **value** (string) - Optional - Name of the value column. Defaults to ‘value’. ### Request Example { "example": "{\"js_dict\": {...}, \"naming\": \"label\", \"value\": \"value\"}" } ### Response #### Success Response (200) - **output** (DataFrame) - Pandas DataFrame with converted data. #### Response Example { "example": "(Pandas DataFrame representation)" } ``` -------------------------------- ### Read JSON-stat data - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Provides a method to read JSON-stat data from different sources including URLs, JSON strings, JSON files, or pandas DataFrames. The `read` class method in `pyjstat.Dataset` handles the parsing and structuring of the data. It also supports SSL verification and optional arguments for data conversion. ```python from pyjstat import Dataset # Example reading from a URL data_from_url = Dataset.read('http://json-stat.org/samples/oecd-canada.json') # Example reading from a JSON string json_string = '{"version": "2.0", ...}' # Your JSON-stat string here data_from_string = Dataset.read(json_string) # Example reading from a pandas DataFrame import pandas as pd df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]}) data_from_df = Dataset.read(df) ``` -------------------------------- ### Write Dataset to JSONstat or DataFrame (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Serializes data from a Dataset object into either JSON-stat format or a pandas DataFrame. The output format and column naming conventions can be specified. ```python from pyjstat import Dataset # Assuming 'data_object' is an instance of Dataset data_object.write(output='jsonstat') data_object.write(output='dataframe', naming='id', value='count') ``` -------------------------------- ### pyjstat.unnest_collection Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Unnests a collection, extracting datasets and converting them to DataFrames. ```APIDOC ## pyjstat.unnest_collection ### Description Unnest collection extracting its datasets and converting them to df. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming collection is an OrderedDict and df_list is an empty list pyjstat.unnest_collection(collection, df_list) # df_list will be populated with pandas DataFrames ``` ### Response #### Success Response (200) - **None** - This function modifies the df_list in place and does not return a value. #### Response Example ```json { "example": "No return value, df_list is modified." } ``` ``` -------------------------------- ### pyjstat.get_dimensions Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves dimensions from input data with optional naming convention. ```APIDOC ## pyjstat.get_dimensions ### Description Get dimensions from input data. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming js_dict is a loaded JSON-stat object and naming is 'label' or 'id' dimensions_list = pyjstat.get_dimensions(js_dict, naming='label') ``` ### Response #### Success Response (200) - **dimensions** (list) - List of pandas DataFrames, each containing category data for a dimension. - **dim_names** (list) - List of strings with dimension names. #### Response Example ```json { "example": { "dimensions": [ "[DataFrame representation]", "[DataFrame representation]" ], "dim_names": [ "dimension1", "dimension2" ] } } ``` ``` -------------------------------- ### Validate Input Parameter (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Validates input parameters, specifically checking if a 'naming' parameter is either 'label' or 'id'. Raises a ValueError if the input is not valid. ```python from pyjstat import check_input try: check_input('label') check_input('id') # check_input('invalid_name') # This would raise ValueError except ValueError as e: print(e) ``` -------------------------------- ### Write JSON-stat data - Python Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Enables writing data from a `pyjstat.Collection` object into either JSON-stat format or as a list of pandas DataFrames. The `write` method allows specifying the desired output format. This is useful for data dissemination or further processing. ```python from pyjstat import Collection # Assuming 'my_collection' is an instance of pyjstat.Collection # Write as JSON-stat json_stat_output = my_collection.write(output='jsonstat') # Write as a list of pandas DataFrames dataframes_list = my_collection.write(output='dataframe_list') ``` -------------------------------- ### Convert Variable to Integer or String Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Converts a given variable (expected to be a string) into either an integer or a string, depending on its content. This is useful for ensuring data types are consistent before further processing. ```python pyjstat.to_int(variable) ``` -------------------------------- ### pyjstat.uniquify Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Returns unique values from a list while preserving the original order. ```APIDOC ## pyjstat.uniquify ### Description Return unique values in a list in the original order. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python my_list = [1, 2, 2, 3, 1, 4] unique_list = pyjstat.uniquify(my_list) ``` ### Response #### Success Response (200) - **list** - List without duplicates preserving original order. #### Response Example ```json { "example": [ 1, 2, 3, 4 ] } ``` ``` -------------------------------- ### from_json_stat Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Decodes JSON-stat formatted data into a list of Pandas DataFrames. ```APIDOC ## POST /from_json_stat ### Description Decode JSON-stat formatted data into pandas.DataFrame object. ### Method POST ### Endpoint /from_json_stat ### Parameters #### Request Body - **datasets** (OrderedDict | list) - Data in JSON-stat format, previously deserialized to a Python object. Both List and OrderedDict are accepted. - **naming** (string) - Optional - Dimension naming. Possible values: ‘label’ or ‘id’. Defaults to ‘label’. - **value** (string) - Optional - Name of the value column. Defaults to ‘value’. ### Request Example { "example": "{\"datasets\": [ ... ], \"naming\": \"label\", \"value\": \"value\"}" } ### Response #### Success Response (200) - **results** (list) - A list of pandas.DataFrame objects with imported data. #### Response Example { "example": "[DataFrame1, DataFrame2, ...]" } ``` -------------------------------- ### Dimension.read Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Reads data from various sources into a Dimension object. ```APIDOC ## POST /Dimension.read ### Description Read data from URL, Dataframe, JSON string/file or OrderedDict. ### Method POST ### Endpoint /Dimension.read ### Parameters #### Request Body - **data** (Pandas DataFrame | string | file | OrderedDict | URL) - Can be a Pandas Dataframe, a JSON string, a JSON file, an OrderedDict or a URL pointing to a JSONstat file. ### Request Example { "example": "(Data in JSONstat format or URL)" } ### Response #### Success Response (200) - **dimension_object** (Dimension) - An object of class Dimension populated with data. #### Response Example { "example": "(Dimension object representation)" } ``` -------------------------------- ### pyjstat.get_dim_index Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves the index for a given dimension from a JSON-stat dataset. ```APIDOC ## pyjstat.get_dim_index ### Description Get index from a given dimension. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming js_dict is a loaded JSON-stat object and dim is a valid dimension name index_df = pyjstat.get_dim_index(js_dict, dim) ``` ### Response #### Success Response (200) - **dim_index** (pandas.DataFrame) - DataFrame with index-based dimension data. #### Response Example ```json { "example": "[DataFrame representation]" } ``` ``` -------------------------------- ### Convert Variable to String Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Converts a given variable (expected to be a string) into a string representation. This function ensures the variable is treated as a string, which can be helpful for consistent data handling. ```python pyjstat.to_str(variable) ``` -------------------------------- ### NumpyEncoder.default Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Custom JSON encoder for Numpy data types. ```APIDOC ## POST /NumpyEncoder.default ### Description Encode by default, handling Numpy data types. ### Method POST ### Endpoint /NumpyEncoder.default ### Parameters #### Request Body - **obj** (any) - The object to encode. ### Request Example { "example": "(Numpy object)" } ### Response #### Success Response (200) - **encoded_object** (any) - The JSON-serializable representation of the object. #### Response Example { "example": "(JSON-serializable representation)" } ``` -------------------------------- ### check_version_2 Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Checks if the JSON-stat version attribute exists and is 2.0 or greater. ```APIDOC ## POST /check_version_2 ### Description Check for json-stat version. Checks if the json-stat version attribute exists and is equal to or greater than 2.0 for a given dataset. ### Method POST ### Endpoint /check_version_2 ### Parameters #### Request Body - **dataset** (OrderedDict) - Data in JSON-stat format, previously deserialized to a Python object. ### Request Example { "example": "(OrderedDict representing JSON-stat data)" } ### Response #### Success Response (200) - **version_check** (boolean) - True if version exists and is >= 2.0, False otherwise. Returns False for datasets without the version attribute. #### Response Example { "example": "true" } ``` -------------------------------- ### Generate DataFrame from JSON-stat Dict (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html A helper method to decode a JSON-stat formatted OrderedDict into a pandas DataFrame. It is intended for internal use within `from_json_stat` but can be used directly. ```python from pyjstat import generate_df # Example JSON-stat data (as OrderedDict or dict) jstat_dict = { 'version': '1.0', 'dimension': { 'age': { 'category': { 'index': [0, 1], 'label': {'0': '0-17', '1': '18+'} } } }, 'value': [100, 200] } df = generate_df(jstat_dict, naming='label', value='population') print(df) ``` -------------------------------- ### Dimension.write Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Writes data from a Dimension object to JSONstat format or a Pandas DataFrame. ```APIDOC ## POST /Dimension.write ### Description Write data from a Dataset object to JSONstat or Pandas Dataframe. ### Method POST ### Endpoint /Dimension.write ### Parameters #### Query Parameters - **output** (string) - Optional - Can accept ‘jsonstat’ or ‘dataframe’. Defaults to ‘jsonstat’. ### Request Example { "example": "{\"output\": \"jsonstat\"}" } ### Response #### Success Response (200) - **data** (string | DataFrame) - Serialized JSONstat or a Pandas Dataframe, depending on the ‘output’ parameter. #### Response Example { "example": "(JSONstat string or Pandas DataFrame representation)" } ``` -------------------------------- ### Hide Fallback Element (JavaScript) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/search.html This JavaScript code snippet targets an HTML element with the ID 'fallback' and hides it. This is typically used to manage the display of content that is only relevant when JavaScript is enabled. ```javascript $('#fallback').hide(); ``` -------------------------------- ### pyjstat.get_dim_label Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Retrieves the label for a given dimension from a JSON-stat dataset. ```APIDOC ## pyjstat.get_dim_label ### Description Get label from a given dimension. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming js_dict is a loaded JSON-stat object, dim is a valid dimension name, and dim_input is 'dataset' label_df = pyjstat.get_dim_label(js_dict, dim, dim_input='dataset') ``` ### Response #### Success Response (200) - **dim_label** (pandas.DataFrame) - DataFrame with label-based dimension data. #### Response Example ```json { "example": "[DataFrame representation]" } ``` ``` -------------------------------- ### Convert Pandas DataFrame to JSON-stat using pyjstat Source: https://github.com/predicador37/pyjstat/blob/master/README.rst This snippet demonstrates how to convert data obtained from a URL into the JSON-stat format using the pyjstat library. It utilizes the requests library to fetch data and OrderedDict for parsing JSON, then prints the results. Note that some metadata might be lost during conversion. ```python from pyjstat import pyjstat import requests from collections import OrderedDict import json EXAMPLE_URL = 'http://json-stat.org/samples/us-labor.json' data = requests.get(EXAMPLE_URL) results = pyjstat.from_json_stat(data.json(object_pairs_hook=OrderedDict)) print (results) print (json.dumps(json.loads(pyjstat.to_json_stat(results)))) ``` -------------------------------- ### Custom JSON Encoding for NumPy (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Provides a custom JSON encoder that handles NumPy data types, allowing them to be serialized into JSON format. This is useful when working with libraries that produce NumPy arrays. ```python import json import numpy as np from pyjstat import NumpyEncoder data = {'array': np.array([1, 2, 3])} json_string = json.dumps(data, cls=NumpyEncoder) print(json_string) ``` -------------------------------- ### Read and Write JSON-stat Collection to List of DataFrames (Python) Source: https://github.com/predicador37/pyjstat/blob/master/README.rst Illustrates parsing a JSON-stat collection from a URL into a list of pandas DataFrames. Requires pyjstat. ```python from pyjstat import pyjstat EXAMPLE_URL = 'http://json-stat.org/samples/collection.json' collection = pyjstat.Collection.read(EXAMPLE_URL) df_list = collection.write('dataframe_list') print(df_list) ``` -------------------------------- ### pyjstat.to_json_stat Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Encodes a pandas DataFrame into JSON-stat format. ```APIDOC ## pyjstat.to_json_stat ### Description Encode pandas.DataFrame object into JSON-stat format. ### Method N/A (Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming input_df is a pandas DataFrame with a single value column json_stat_output = pyjstat.to_json_stat(input_df, value='value', output='dict', version='2.0') ``` ### Response #### Success Response (200) - **output** (string) - String with JSON-stat object. #### Response Example ```json { "example": "{\"version\": \"2.0\", \"class\": \"dataset\", \"label\": \"My Data\", \"value\": [10, 20, 30]}" } ``` ``` -------------------------------- ### Check JSON-stat Version (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Verifies if a given dataset, deserialized from JSON-stat format, has a version attribute that is equal to or greater than 2.0. Returns False for datasets without a version attribute. ```python from pyjstat import check_version_2 # Example dataset with version 2.0 valid_dataset = {'version': '2.0', 'value': [1, 2]} # Example dataset without version no_version_dataset = {'value': [3, 4]} print(check_version_2(valid_dataset)) print(check_version_2(no_version_dataset)) ``` -------------------------------- ### Read JSON-stat to Pandas DataFrame (Older Versions - Python) Source: https://github.com/predicador37/pyjstat/blob/master/README.rst Demonstrates reading a JSON-stat file into a pandas DataFrame using older pyjstat syntax (version 0.3.5 and older). This method is deprecated. Requires pyjstat, requests, and collections.OrderedDict. ```python from pyjstat import pyjstat import requests from collections import OrderedDict EXAMPLE_URL = 'http://json-stat.org/samples/us-labor.json' data = requests.get(EXAMPLE_URL) ``` -------------------------------- ### get_df_row Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Generates row dimension values for a Pandas DataFrame. ```APIDOC ## POST /get_df_row ### Description Generate row dimension values for a pandas dataframe. ### Method POST ### Endpoint /get_df_row ### Parameters #### Request Body - **dimensions** (list) - List of pandas dataframes with dimension labels generated by get_dim_label or get_dim_index methods. - **naming** (string) - Optional - Dimension naming. Possible values: ‘label’ or ‘id’. Defaults to ‘label’. - **i** (int) - Optional - Dimension list iteration index. Default is 0. - **record** (list) - Optional - List of values representing a pandas dataframe row, except for the value column. Default is empty. ### Request Example { "example": "{\"dimensions\": [...], \"naming\": \"label\", \"i\": 0, \"record\": []}" } ### Response #### Success Response (200) - **yielded_values** (list) - Yields dimension values for a pandas dataframe row. #### Response Example { "example": "(List of dimension values for a row)" } ``` -------------------------------- ### Generate DataFrame Row Values (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Recursively generates dimension values for a single row of a pandas DataFrame based on provided dimension labels. It handles 'label' or 'id' naming conventions. ```python from pyjstat import get_df_row # Example dimensions structure (simplified) dimensions_data = [ {'label': ['A', 'B'], 'id': [0, 1]}, {'label': ['X', 'Y'], 'id': [10, 20]} ] # Assuming dimensions_data is processed to match expected input format # This is a conceptual example, actual input structure may vary # For illustration, let's assume a simplified structure where get_df_row operates on indices # A more complete example would involve get_dim_label or get_dim_index first. # Conceptual usage (actual implementation details might differ based on library's internal data structures): # for row_values in get_df_row(processed_dimensions, naming='label'): # print(row_values) # Since get_df_row is a generator and its input structure is complex, a direct runnable example is challenging without the full context. # However, its purpose is to yield lists of values that form a row in the DataFrame. ``` -------------------------------- ### Decode JSON-stat to DataFrame (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Converts JSON-stat formatted data (as an OrderedDict or list) into a pandas DataFrame. Allows specifying dimension naming and the value column name. Returns a list of DataFrames. ```python from pyjstat import from_json_stat # Example JSON-stat data jstat_data = { 'version': '2.0', 'class': 'dataset', 'label': {'en': 'Example Data'}, 'dimension': { 'id': { 'category': { 'index': {'A': 0, 'B': 1}, 'label': {'en': {'A': 'Category A', 'B': 'Category B'}} } }, 'time': { 'category': { 'index': {'2020': 0, '2021': 1}, 'label': {'en': {'2020': '2020', '2021': '2021'}} } } }, 'value': [10, 20, 30, 40] } dataframes = from_json_stat(jstat_data, naming='label', value='count') for df in dataframes: print(df) ``` -------------------------------- ### Write Dimension to JSONstat or DataFrame (Python) Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Serializes a Dimension object's data into JSON-stat format or a pandas DataFrame. The output format can be specified as either 'jsonstat' or 'dataframe'. ```python from pyjstat import Dimension # Assuming 'dimension_object' is an instance of Dimension dimension_object.write(output='jsonstat') dimension_object.write(output='dataframe') ``` -------------------------------- ### Unnest JSON-stat Collection to DataFrames Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Extracts datasets from a JSON-stat formatted collection (deserialized into a Python object) and converts them into pandas DataFrames. These DataFrames are appended to a provided list. This function is essential for processing nested JSON-stat data structures. ```python pyjstat.unnest_collection(collection, df_list) ``` -------------------------------- ### Encode pandas DataFrame to JSON-stat Format Source: https://github.com/predicador37/pyjstat/blob/master/docs/build/html/modules.html Encodes a pandas DataFrame into the JSON-stat format. The DataFrame must contain exactly one value column. Options allow specifying the value column name, the output format ('list' or 'dict'), and the JSON-stat version. Returns a string representation of the JSON-stat object. ```python pyjstat.to_json_stat(input_df, value='value', output='list', version='1.3') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.