jsonpath-nz


Namejsonpath-nz JSON
Version 0.1.2 PyPI version JSON
download
home_pagehttps://github.com/arusatech/jsonpath-nz
SummaryA Python library for bidirectional conversion between JSON objects and JSONPath expressions
upload_time2025-01-05 08:36:51
maintainerNone
docs_urlNone
authorYakub Mohammad
requires_python<4.0,>=3.8.1
licenseMIT
keywords json jsonpath converter dict
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # JSONPath-NZ (NextZen)

A Python library for bidirectional conversion between JSON objects and JSONPath expressions, with support for complex filter conditions and array handling.
- `Author` : Yakub Mohammad (yakub@arusatech.com , arusatechnology@gmail.com)
- `Organization` : AR USA LLC
- `License` : MIT

## Features

### Two-way conversion between JSON and JSONPath expressions:
- Convert JSONPath expressions to JSON objects (`parse_jsonpath`)
- Convert JSON objects to JSONPath expressions (`parse_dict`)
- Support for complex filter conditions using `extend` parameter
- Handle nested objects and arrays
- Support array indexing and empty objects
- Maintain data structure integrity

### JSON Pretty Printing
- The package includes a convenient JSON pretty printing utility `jprint` that handles various data formats and provides flexible output options.

#### Parameters

- `data`: The data to print (dict, list, string, or any object)
- `load`: Set to `True` when input is a JSON string that needs parsing
- `marshall`: Set to `True` to convert non-JSON-serializable objects to strings
- `indent`: Number of spaces for indentation (default: 2)

### Enhanced Python Logger
- A flexible basic logging utility `log` that uses Python's built-in logging functionality with additional features like file capture and detailed tracebacks.
- Console and file logging support
- Capture specific log messages to file
- Detailed traceback information
- Consistent formatting across console and file outputs
- File name and line number tracking
- Dynamic log file configuration (example : `log.config(log_file_name)`)

#### Log Levels
- `log.debug(msg)` - Detailed information for debugging
- `log.info(msg)` - General information about program execution
- `log.warning(msg)` - Warning messages for potentially problematic situations
- `log.error(msg)` - Error messages for serious problems
- `log.critical(msg)` - Critical messages for fatal errors
- `log.traceback(e)` - Detailed exception information can be used in try/except blocks

## Installation

```bash
pip install jsonpath-nz
```

## Usage

### Converting JSONPath to Dictionary (`parse_jsonpath(<Dict of JSONPath>,extend=<extend filter dictionary>)`)
### Converting Dictionary to JSONPath (`parse_dict(<Dictionary>,extend=<extend filter dictionary>)`)

- See the [tests/test_parse_jsonpath.py and tests/test_parse_dict.py] files for examples.

- Define extend parameter for filter conditions

# JSONPath Extend Filter given as parameter 

The extend filter in JSONPath allows complex filtering of arrays based on multiple conditions. It uses the syntax:

[?(@.field1 == 'value1' && @.field2 == 'value2')]

Example:
`$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact`

This filters array elements where:
- firstName equals 'John' AND
- lastName equals 'wright'

Key features:
- Uses @ to reference current element
- Supports multiple conditions with && (AND)
- Can access nested properties
- Returns matching elements only

## API Reference

### parse_jsonpath(manifest, extend=None)

Converts JSONPath expressions to a dictionary structure.

Parameters:
- `manifest` (dict): Dictionary with JSONPath expressions as keys and values
- `extend` (dict, optional): Dictionary specifying filter conditions for arrays

Returns:
- dict: Processed dictionary structure

Example:

```python
from jsonpath_nz import parse_jsonpath, jprint
JSONPath expressions
jsonpath_data = {
    "$.store.book[1].author": "Yakub Mohammad",
    "$.store.local": "False",
    "$.channel": "online",
    "$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'Doe')].contact": "9876543210",
    "$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact": "9876543211"
}
extend = {
    "borrower": ["firstName", "lastName"]
}
result = parse_jsonpath(jsonpath_data, extend=extend)
jprint(result)
```
Output:
```
{
  "store": {
    "book": [
      {},
      {
        "author": "Yakub Mohammad"
      }
    ],
    "local": "False"
  },
  "channel": "online",
  "loanApplication": {
    "borrower": [
      {
        "firstName": "(John)",
        "lastName": "(Doe)",
        "contact": "9876543210"
      },
      {
        "firstName": "(John)",
        "lastName": "(wright)",
        "contact": "9876543211"
      }
    ]
  }
}
```

### parse_dict(data, parent_path='$', paths=None, extend=None)

Converts a dictionary to JSONPath expressions.

Parameters:
- `data` (dict): Input dictionary to convert
- `parent_path` (str, optional): Base JSONPath. Defaults to '$'
- `paths` (dict, optional): Dictionary to store results
- `extend` (dict, optional): Dictionary specifying filter fields for arrays

Returns:
- dict: Dictionary with JSONPath expressions as keys and values

Example:

```python
from jsonpath_nz import parse_dict, jprint

# Dictionary to convert
dict_data = {
    "store": {"book": [{"author": "Yakub Mohammad"}, {"category": "Fiction"}]},
    "channel": "online",
    "loanApplication": {'borrower': [
        {'firstName': 'John', 'lastName': 'Doe', 'contact': '9876543210'},
        {'firstName': 'John', 'lastName': 'wright', 'contact': '9876543211'}]}
}

extend = {
    "borrower": ["firstName", "lastName"]
}

result = parse_dict(dict_data, extend=None)
jprint(result)
```

Output:
```bash
{
  "$.store.book[1].author": "Yakub Mohammad",
  "$.store.local": "False",
  "$.channel": "online",
  "$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'Doe')].contact": "9876543210",
  "$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact": "9876543211"
}
```

## Error Handling

Both functions include error handling for:
- Invalid JSONPath syntax
- Unbalanced brackets or quotes
- Missing required fields
- Invalid filter conditions

## JSON Pretty Printing

- In the above example of parse_jsonpath and parse_dict functions, the output is printed using the `jprint` function.

## Logging

- The `log` function is used to log messages to the console and file.
- See the [tests/test_log.py] file for examples.

Example:

```python
from jsonpath_nz import log
log.config("app.log") # this is optional(default log capture to <temp directory>/arlog_<timestamp>.log)
log.info("This is a test message")
log.error("This is an error message")
log.critical("This is a critical message", capture=True) # this will capture to file
log.warning("This is a warning message" , 1) # this will capture to file
log.debug("This is a debug message")
def test_traceback():   
    try:
        #divide by zero
        a = 1/0
        raise Exception("This is a test exception")
    except Exception as e:
        log.traceback(e)
        log.error("This is an trace back message--",1)
test_traceback()
```

Output:
```
2025-01-05 00:21:31,881 - INFO      [test_log.py:12] This is a test message
2025-01-05 00:21:31,881 - ERROR     [test_log.py:13] This is an error message
2025-01-05 00:21:31,881 - CRITICAL  [test_log.py:14] This is a critical message
2025-01-05 00:21:31,882 - WARNING   [test_log.py:15] This is a warning message
2025-01-05 00:21:31,882 - DEBUG     [test_log.py:16] This is a debug message
2025-01-05 00:21:31,883 - ERROR     [test_log.py:25] ======= TRACEBACK =======
TRACEBACK: << test_traceback >> [C:\Users\arusa\tools\GIT\jsonpath-nz\tests\test_log.py:22]
ZERODIVISIONERROR: division by zero
2025-01-05 00:21:31,883 - ERROR     [test_log.py:26] This is an trace back message--
```











            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/arusatech/jsonpath-nz",
    "name": "jsonpath-nz",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8.1",
    "maintainer_email": null,
    "keywords": "json, jsonpath, converter, dict",
    "author": "Yakub Mohammad",
    "author_email": "yakub@arusatech.com> <arusatechnology@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/15/6d/147dc0547aea58423df2dbad71f28714bb9d1b59b2ea54254b18222296da/jsonpath_nz-0.1.2.tar.gz",
    "platform": null,
    "description": "# JSONPath-NZ (NextZen)\n\nA Python library for bidirectional conversion between JSON objects and JSONPath expressions, with support for complex filter conditions and array handling.\n- `Author` : Yakub Mohammad (yakub@arusatech.com , arusatechnology@gmail.com)\n- `Organization` : AR USA LLC\n- `License` : MIT\n\n## Features\n\n### Two-way conversion between JSON and JSONPath expressions:\n- Convert JSONPath expressions to JSON objects (`parse_jsonpath`)\n- Convert JSON objects to JSONPath expressions (`parse_dict`)\n- Support for complex filter conditions using `extend` parameter\n- Handle nested objects and arrays\n- Support array indexing and empty objects\n- Maintain data structure integrity\n\n### JSON Pretty Printing\n- The package includes a convenient JSON pretty printing utility `jprint` that handles various data formats and provides flexible output options.\n\n#### Parameters\n\n- `data`: The data to print (dict, list, string, or any object)\n- `load`: Set to `True` when input is a JSON string that needs parsing\n- `marshall`: Set to `True` to convert non-JSON-serializable objects to strings\n- `indent`: Number of spaces for indentation (default: 2)\n\n### Enhanced Python Logger\n- A flexible basic logging utility `log` that uses Python's built-in logging functionality with additional features like file capture and detailed tracebacks.\n- Console and file logging support\n- Capture specific log messages to file\n- Detailed traceback information\n- Consistent formatting across console and file outputs\n- File name and line number tracking\n- Dynamic log file configuration (example : `log.config(log_file_name)`)\n\n#### Log Levels\n- `log.debug(msg)` - Detailed information for debugging\n- `log.info(msg)` - General information about program execution\n- `log.warning(msg)` - Warning messages for potentially problematic situations\n- `log.error(msg)` - Error messages for serious problems\n- `log.critical(msg)` - Critical messages for fatal errors\n- `log.traceback(e)` - Detailed exception information can be used in try/except blocks\n\n## Installation\n\n```bash\npip install jsonpath-nz\n```\n\n## Usage\n\n### Converting JSONPath to Dictionary (`parse_jsonpath(<Dict of JSONPath>,extend=<extend filter dictionary>)`)\n### Converting Dictionary to JSONPath (`parse_dict(<Dictionary>,extend=<extend filter dictionary>)`)\n\n- See the [tests/test_parse_jsonpath.py and tests/test_parse_dict.py] files for examples.\n\n- Define extend parameter for filter conditions\n\n# JSONPath Extend Filter given as parameter \n\nThe extend filter in JSONPath allows complex filtering of arrays based on multiple conditions. It uses the syntax:\n\n[?(@.field1 == 'value1' && @.field2 == 'value2')]\n\nExample:\n`$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact`\n\nThis filters array elements where:\n- firstName equals 'John' AND\n- lastName equals 'wright'\n\nKey features:\n- Uses @ to reference current element\n- Supports multiple conditions with && (AND)\n- Can access nested properties\n- Returns matching elements only\n\n## API Reference\n\n### parse_jsonpath(manifest, extend=None)\n\nConverts JSONPath expressions to a dictionary structure.\n\nParameters:\n- `manifest` (dict): Dictionary with JSONPath expressions as keys and values\n- `extend` (dict, optional): Dictionary specifying filter conditions for arrays\n\nReturns:\n- dict: Processed dictionary structure\n\nExample:\n\n```python\nfrom jsonpath_nz import parse_jsonpath, jprint\nJSONPath expressions\njsonpath_data = {\n    \"$.store.book[1].author\": \"Yakub Mohammad\",\n    \"$.store.local\": \"False\",\n    \"$.channel\": \"online\",\n    \"$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'Doe')].contact\": \"9876543210\",\n    \"$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact\": \"9876543211\"\n}\nextend = {\n    \"borrower\": [\"firstName\", \"lastName\"]\n}\nresult = parse_jsonpath(jsonpath_data, extend=extend)\njprint(result)\n```\nOutput:\n```\n{\n  \"store\": {\n    \"book\": [\n      {},\n      {\n        \"author\": \"Yakub Mohammad\"\n      }\n    ],\n    \"local\": \"False\"\n  },\n  \"channel\": \"online\",\n  \"loanApplication\": {\n    \"borrower\": [\n      {\n        \"firstName\": \"(John)\",\n        \"lastName\": \"(Doe)\",\n        \"contact\": \"9876543210\"\n      },\n      {\n        \"firstName\": \"(John)\",\n        \"lastName\": \"(wright)\",\n        \"contact\": \"9876543211\"\n      }\n    ]\n  }\n}\n```\n\n### parse_dict(data, parent_path='$', paths=None, extend=None)\n\nConverts a dictionary to JSONPath expressions.\n\nParameters:\n- `data` (dict): Input dictionary to convert\n- `parent_path` (str, optional): Base JSONPath. Defaults to '$'\n- `paths` (dict, optional): Dictionary to store results\n- `extend` (dict, optional): Dictionary specifying filter fields for arrays\n\nReturns:\n- dict: Dictionary with JSONPath expressions as keys and values\n\nExample:\n\n```python\nfrom jsonpath_nz import parse_dict, jprint\n\n# Dictionary to convert\ndict_data = {\n    \"store\": {\"book\": [{\"author\": \"Yakub Mohammad\"}, {\"category\": \"Fiction\"}]},\n    \"channel\": \"online\",\n    \"loanApplication\": {'borrower': [\n        {'firstName': 'John', 'lastName': 'Doe', 'contact': '9876543210'},\n        {'firstName': 'John', 'lastName': 'wright', 'contact': '9876543211'}]}\n}\n\nextend = {\n    \"borrower\": [\"firstName\", \"lastName\"]\n}\n\nresult = parse_dict(dict_data, extend=None)\njprint(result)\n```\n\nOutput:\n```bash\n{\n  \"$.store.book[1].author\": \"Yakub Mohammad\",\n  \"$.store.local\": \"False\",\n  \"$.channel\": \"online\",\n  \"$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'Doe')].contact\": \"9876543210\",\n  \"$.loanApplication.borrower[?(@.firstName == 'John' && @.lastName == 'wright')].contact\": \"9876543211\"\n}\n```\n\n## Error Handling\n\nBoth functions include error handling for:\n- Invalid JSONPath syntax\n- Unbalanced brackets or quotes\n- Missing required fields\n- Invalid filter conditions\n\n## JSON Pretty Printing\n\n- In the above example of parse_jsonpath and parse_dict functions, the output is printed using the `jprint` function.\n\n## Logging\n\n- The `log` function is used to log messages to the console and file.\n- See the [tests/test_log.py] file for examples.\n\nExample:\n\n```python\nfrom jsonpath_nz import log\nlog.config(\"app.log\") # this is optional(default log capture to <temp directory>/arlog_<timestamp>.log)\nlog.info(\"This is a test message\")\nlog.error(\"This is an error message\")\nlog.critical(\"This is a critical message\", capture=True) # this will capture to file\nlog.warning(\"This is a warning message\" , 1) # this will capture to file\nlog.debug(\"This is a debug message\")\ndef test_traceback():   \n    try:\n        #divide by zero\n        a = 1/0\n        raise Exception(\"This is a test exception\")\n    except Exception as e:\n        log.traceback(e)\n        log.error(\"This is an trace back message--\",1)\ntest_traceback()\n```\n\nOutput:\n```\n2025-01-05 00:21:31,881 - INFO      [test_log.py:12] This is a test message\n2025-01-05 00:21:31,881 - ERROR     [test_log.py:13] This is an error message\n2025-01-05 00:21:31,881 - CRITICAL  [test_log.py:14] This is a critical message\n2025-01-05 00:21:31,882 - WARNING   [test_log.py:15] This is a warning message\n2025-01-05 00:21:31,882 - DEBUG     [test_log.py:16] This is a debug message\n2025-01-05 00:21:31,883 - ERROR     [test_log.py:25] ======= TRACEBACK =======\nTRACEBACK: << test_traceback >> [C:\\Users\\arusa\\tools\\GIT\\jsonpath-nz\\tests\\test_log.py:22]\nZERODIVISIONERROR: division by zero\n2025-01-05 00:21:31,883 - ERROR     [test_log.py:26] This is an trace back message--\n```\n\n\n\n\n\n\n\n\n\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A Python library for bidirectional conversion between JSON objects and JSONPath expressions",
    "version": "0.1.2",
    "project_urls": {
        "Documentation": "https://github.com/arusatech/jsonpath-nz#readme",
        "Homepage": "https://github.com/arusatech/jsonpath-nz",
        "Repository": "https://github.com/arusatech/jsonpath-nz"
    },
    "split_keywords": [
        "json",
        " jsonpath",
        " converter",
        " dict"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fa97eb3604f3e5dcaaf937441ab39989d9c48ec92f4849ff1fa25e8f2a0b383a",
                "md5": "ce00e7787a94f1b785daf20fd84c6d6c",
                "sha256": "553b59923c6be3568040c475615a85afebefa1f9563aaddf2a07922b819dc9fe"
            },
            "downloads": -1,
            "filename": "jsonpath_nz-0.1.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ce00e7787a94f1b785daf20fd84c6d6c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8.1",
            "size": 10778,
            "upload_time": "2025-01-05T08:36:49",
            "upload_time_iso_8601": "2025-01-05T08:36:49.838823Z",
            "url": "https://files.pythonhosted.org/packages/fa/97/eb3604f3e5dcaaf937441ab39989d9c48ec92f4849ff1fa25e8f2a0b383a/jsonpath_nz-0.1.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "156d147dc0547aea58423df2dbad71f28714bb9d1b59b2ea54254b18222296da",
                "md5": "df72bcf79c276b580051538d86246011",
                "sha256": "74173caa0d8649763efca27d58c3fc9c58eaa237a9ad7c2cd90423dc4eeadd46"
            },
            "downloads": -1,
            "filename": "jsonpath_nz-0.1.2.tar.gz",
            "has_sig": false,
            "md5_digest": "df72bcf79c276b580051538d86246011",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8.1",
            "size": 9972,
            "upload_time": "2025-01-05T08:36:51",
            "upload_time_iso_8601": "2025-01-05T08:36:51.883176Z",
            "url": "https://files.pythonhosted.org/packages/15/6d/147dc0547aea58423df2dbad71f28714bb9d1b59b2ea54254b18222296da/jsonpath_nz-0.1.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-05 08:36:51",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "arusatech",
    "github_project": "jsonpath-nz",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "jsonpath-nz"
}
        
Elapsed time: 0.39032s