partial-json-parser icon indicating copy to clipboard operation
partial-json-parser copied to clipboard

[feat] Add support for parsing JSON with text prefix and postfix

Open ArmykOliva opened this issue 11 months ago • 6 comments

Add PREFIX and POSTFIX options for handling text around JSON

This PR adds support for parsing JSON that is embedded within other text by introducing two new options:

  • PREFIX: Allows text before the JSON string starts (e.g. This is your JSON: {"key": "value"})
  • POSTFIX: Allows text after the JSON string ends (e.g. {"key": "value"} - end of JSON)

Implementation Details

  • Added PREFIX and POSTFIX flags to the Allow enum
  • Modified fix_fast() to handle trimming of non-JSON content:
    • PREFIX: Finds the first { or [ character to identify JSON start
    • POSTFIX: Finds the last } or ] character to identify JSON end
  • Automatically enables STR flag when PREFIX/POSTFIX is used to handle partial strings within the JSON

Example Usage

from partial_json_parser import loads, PREFIX, POSTFIX

# Handle text before JSON
result = loads('This is your JSON: {"key": "value"}', PREFIX)
print(result)  # {'key': 'value'}

# Handle text after JSON
result = loads('{"key": "value"} - end of JSON', POSTFIX)
print(result)  # {'key': 'value'}

# Handle both
result = loads('Start of JSON: {"key": "value"} - end of JSON', PREFIX | POSTFIX)
print(result)  # {'key': 'value'}

Summary by Sourcery

Add support for parsing JSON with text prefix and postfix using the PREFIX and POSTFIX options.

New Features:

  • Added support for parsing JSON embedded within other text using the new PREFIX and POSTFIX options in the loads function. The PREFIX option handles text before the JSON, while POSTFIX handles text after the JSON.

Tests:

  • Updated tests to cover the new PREFIX and POSTFIX options.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for parsing JSON strings with surrounding text
    • Introduced PREFIX and POSTFIX options to handle JSON extraction from complex strings
  • Documentation

    • Updated README with new parsing option examples
    • Expanded library documentation to explain new parsing capabilities
  • Improvements

    • Enhanced JSON parsing logic to handle more flexible input formats
    • Improved flexibility in extracting valid JSON from text with extraneous content

ArmykOliva avatar Jan 28 '25 17:01 ArmykOliva

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

Reviewer's Guide by Sourcery

This pull request introduces the ability to parse JSON strings that are embedded within other text. It adds two new options, PREFIX and POSTFIX, to handle text before and after the JSON string, respectively. The implementation modifies the fix_fast function to trim non-JSON content based on these options and automatically enables the STR flag when PREFIX or POSTFIX is used.

Sequence diagram for JSON parsing with PREFIX and POSTFIX

sequenceDiagram
    participant Client
    participant Parser
    participant FixFast

    Client->>Parser: loads('Text: {"key": "value"} End', PREFIX | POSTFIX)
    Parser->>FixFast: fix_fast(text, allow)
    Note over FixFast: Check for PREFIX
    FixFast->>FixFast: Find first { or [
    Note over FixFast: Check for POSTFIX
    FixFast->>FixFast: Find last } or ]
    Note over FixFast: Enable STR flag
    FixFast->>FixFast: Process trimmed JSON
    FixFast-->>Parser: Return fixed JSON
    Parser-->>Client: Return parsed result

Class diagram showing Allow enum changes

classDiagram
    class Allow {
        <<enumeration>>
        STR
        NUM
        NULL
        BOOL
        ARR
        OBJ
        NAN
        INFINITY
        _INFINITY
        PREFIX*
        POSTFIX*
        INF
        SPECIAL
        ATOM
        COLLECTION
        ALL
    }
    note for Allow "* New flags added
ALL now includes PREFIX and POSTFIX"

File-Level Changes

Change Details Files
Added PREFIX and POSTFIX flags to the Allow enum.
  • Added PREFIX and POSTFIX as new members of the Allow enum.
  • Updated ALL to include PREFIX and POSTFIX.
src/partial_json_parser/core/options.py
Modified fix_fast() to handle trimming of non-JSON content based on PREFIX and POSTFIX flags.
  • Implemented logic to find the first { or [ character to identify the start of the JSON string when PREFIX is enabled.
  • Implemented logic to find the last } or ] character to identify the end of the JSON string when POSTFIX is enabled.
  • Automatically enables the STR flag when PREFIX or POSTFIX is used.
src/partial_json_parser/core/myelin.py
Added documentation for the new PREFIX and POSTFIX options.
  • Added a section explaining how to use the PREFIX and POSTFIX options.
  • Provided example usage of the new options.
README.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an issue from a review comment by replying to it. You can also reply to a review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull request title to generate a title at any time. You can also comment @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in the pull request body to generate a PR summary at any time exactly where you want it. You can also comment @sourcery-ai summary on the pull request to (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the pull request to resolve all Sourcery comments. Useful if you've already addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull request to dismiss all existing Sourcery reviews. Especially useful if you want to start fresh with a new review - don't forget to comment @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

  • Contact our support team for questions or feedback.
  • Visit our documentation for detailed guides and information.
  • Keep in touch with the Sourcery team by following us on X/Twitter, LinkedIn or GitHub.

sourcery-ai[bot] avatar Jan 28 '25 17:01 sourcery-ai[bot]

Walkthrough

The pull request enhances the partial-json-parser library by introducing two new parsing options: PREFIX and POSTFIX. These options enable the library to extract JSON content from strings that contain additional text before or after the actual JSON. The changes modify the core parsing logic to support locating JSON by finding the first or last occurrence of braces or brackets, expanding the library's flexibility in handling partially embedded JSON strings.

Changes

File Change Summary
README.md Added documentation for new PREFIX and POSTFIX parsing options
src/partial_json_parser/core/options.py - Added PREFIX and POSTFIX enum members to Allow class
- Updated ALL to include new options
- Added new options to __all__ list
src/partial_json_parser/core/myelin.py - Enhanced fix_fast function to handle prefix and postfix conditions
- Added new fix_fast_old function with alternative parsing approach

Sequence Diagram

sequenceDiagram
    participant User
    participant Parser
    participant JSONExtractor
    User->>Parser: loads(text, allow=[PREFIX, POSTFIX])
    Parser->>JSONExtractor: Locate first '{' or '['
    Parser->>JSONExtractor: Locate last '}' or ']'
    JSONExtractor-->>Parser: Extracted JSON string
    Parser-->>User: Parsed JSON object

Poem

🐰 A parsing rabbit's delight, JSON hidden, now in clear sight! Prefix, postfix, no longer a fright, Braces and brackets, we'll parse just right! Hop through the text with magical might! 🔍

✨ Finishing Touches
  • [ ] 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar Jan 28 '25 17:01 coderabbitai[bot]

Thank you! I am celebrating the Chinese new year these days, and will take a look when I have time~

CNSeniorious000 avatar Jan 28 '25 18:01 CNSeniorious000

Unit tests should also be updated to support this change. But IMO it's a very useful feature. At least for me since llms always like to answer with: """ Here is your json!

{your actual json}

"""

which is annoying

ArmykOliva avatar Jan 29 '25 10:01 ArmykOliva

The postfix doens't work and breaks the actual program. upon further evaluation. I think postfix pruning is kind of impossible during the llm generation. Prefix is easily fixed though.

ArmykOliva avatar Feb 04 '25 10:02 ArmykOliva