Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: with-action
Choose a base branch
from

Conversation

ArmykOliva
Copy link

@ArmykOliva ArmykOliva commented Jan 28, 2025

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

Copy link

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

Copy link
Contributor

sourcery-ai bot commented Jan 28, 2025

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
Loading

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"
Loading

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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ArmykOliva - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The fix_fast_old() function appears to be left in the code and should be removed
  • Consider adding documentation about limitations of the PREFIX/POSTFIX parsing approach when dealing with nested JSON structures or strings containing braces
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Review instructions: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +26 to +30
first_brace = json_string.find('{')
first_bracket = json_string.find('[')

if first_brace != -1 and (first_bracket == -1 or first_brace < first_bracket):
json_string = json_string[first_brace:]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Consider handling escaped braces/brackets in string literals when searching for JSON start/end

The current implementation using find() doesn't account for escaped characters in string literals. This could lead to incorrect parsing if the input contains escaped braces or brackets. Consider using a string-aware parsing approach similar to the old version.

@@ -20,6 +20,78 @@ def join_closing_tokens(stack: List[Tuple[int, str]]):

def fix_fast(json_string: str, allow_partial: Union[Allow, int] = ALL):
allow = Allow(allow_partial)

# Handle PREFIX by finding first { or [
if PREFIX in allow:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): Consider combining PREFIX and POSTFIX string operations to reduce string slicing

When both PREFIX and POSTFIX are enabled, we perform multiple string slicing operations. Consider calculating both bounds first and then performing a single slice operation.

Suggested implementation:

    allow = Allow(allow_partial)

    # Calculate bounds for both PREFIX and POSTFIX at once
    start_idx = 0
    end_idx = len(json_string)

    if PREFIX in allow:
        first_brace = json_string.find('{')
        first_bracket = json_string.find('[')
        if first_brace != -1 and (first_bracket == -1 or first_brace < first_bracket):
            start_idx = first_brace
        elif first_bracket != -1:
            start_idx = first_bracket

    if POSTFIX in allow:
        last_brace = json_string.rfind('}')
        last_bracket = json_string.rfind(']')

The code will need one additional change after the shown section:

  1. Add a single slice operation at the end: json_string = json_string[start_idx:end_idx]
  2. The existing POSTFIX handling code will need to be modified to set end_idx instead of directly slicing the string

print(result) # Outputs: {'key': 'value'}
```

Note that `PREFIX` looks for the first `{` or `[` character and `POSTFIX` looks for the last `}` or `]` character to determine the JSON boundaries.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Clarify the behavior when the starting/ending characters are not found.

It would be helpful to explicitly state what happens if the { or [ character is not found when using PREFIX, or if the } or ] character is not found when using POSTFIX. Does it raise an error? Or treat the whole string as JSON?

Suggested change
Note that `PREFIX` looks for the first `{` or `[` character and `POSTFIX` looks for the last `}` or `]` character to determine the JSON boundaries.
Note that `PREFIX` looks for the first `{` or `[` character and `POSTFIX` looks for the last `}` or `]` character to determine the JSON boundaries. If these characters are not found:
- With `PREFIX`: A `JSONDecodeError` is raised if no starting `{` or `[` is found
- With `POSTFIX`: A `JSONDecodeError` is raised if no ending `}` or `]` is found
Examples:
```python
# This will raise JSONDecodeError since there's no starting { or [
loads('This has no JSON', PREFIX)
# This will raise JSONDecodeError since there's no ending } or ]
loads('{"incomplete": "json"', POSTFIX)

@@ -20,6 +20,78 @@ def join_closing_tokens(stack: List[Tuple[int, str]]):

def fix_fast(json_string: str, allow_partial: Union[Allow, int] = ALL):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): Consider extracting the prefix/postfix handling logic into helper functions to improve readability and maintainability.

The code can be simplified by extracting the token handling logic into focused helper functions and consolidating flag management. Here's a suggested refactoring:

def _find_prefix_start(json_string: str) -> int:
    first_brace = json_string.find('{')
    first_bracket = json_string.find('[')

    if first_brace != -1 and (first_bracket == -1 or first_brace < first_bracket):
        return first_brace
    return first_bracket if first_bracket != -1 else 0

def _find_postfix_end(json_string: str) -> int:
    last_brace = json_string.rfind('}')
    last_bracket = json_string.rfind(']')

    if last_brace != -1 and (last_bracket == -1 or last_brace > last_bracket):
        return last_brace + 1
    return last_bracket + 1 if last_bracket != -1 else len(json_string)

def fix_fast(json_string: str, allow_partial: Union[Allow, int] = ALL):
    allow = Allow(allow_partial)

    # Enable STR when handling PREFIX/POSTFIX
    if PREFIX in allow or POSTFIX in allow:
        allow |= STR

    # Apply PREFIX/POSTFIX handling
    start = _find_prefix_start(json_string) if PREFIX in allow else 0
    end = _find_postfix_end(json_string) if POSTFIX in allow else len(json_string)

    return _fix(json_string[start:end], allow, True)

This refactoring:

  1. Extracts prefix/postfix logic into focused helper functions
  2. Consolidates flag handling at the start
  3. Simplifies the main function flow
  4. Eliminates the need for fix_fast_old

Copy link

coderabbitai bot commented Jan 28, 2025

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
Loading

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/partial_json_parser/core/myelin.py (3)

44-47: Align approach with fix_fast_old for consistency.
Currently, fix_fast always sets STR when PREFIX or POSTFIX is used, while fix_fast_old removes these flags after processing. Consider consolidating both approaches or adding clarifying comments about their intended differences.


55-64: Reduce duplicated logic for prefix handling.
fix_fast_old repeats the prefix search code used in fix_fast. Extracting shared logic into a helper function could simplify maintenance and minimize duplication.


65-94: Unify string-escape checks to avoid potential edge cases.
The code at line 79 toggles in_string based on a single backslash check. Meanwhile, is_escaped() provides a more robust mechanism for evaluating escaped quotes. Consider consolidating these checks to ensure all valid escape sequences are properly handled.

- if char == '"' and (i == 0 or json_string[i-1] != '\\'):
-     in_string = not in_string
+ if char == '"' and not is_escaped(i):
+     in_string = not in_string
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d835069 and a7d38ff.

📒 Files selected for processing (3)
  • README.md (2 hunks)
  • src/partial_json_parser/core/myelin.py (1 hunks)
  • src/partial_json_parser/core/options.py (3 hunks)
🔇 Additional comments (6)
src/partial_json_parser/core/myelin.py (2)

24-33: Consider explicit handling when braces/brackets are absent.
If the input string contains no '{' or '[', the current logic proceeds without any trimming, which might lead to unexpected or partial results elsewhere.


34-43: Double-check behavior for missing closing tokens.
Similar to the prefix logic, if there is no '}' or ']', the function makes no modifications. Verify whether a fallback or error handling is needed for strings that never properly close a JSON scope.

src/partial_json_parser/core/options.py (2)

16-17: New flags for PREFIX and POSTFIX look suitable.
Adding these members to the enum and incorporating them into ALL extends the parser's ability to handle text around JSON precisely as intended.

Also applies to: 23-23


40-41: Exporting PREFIX and POSTFIX in the module's namespace.
This makes them readily accessible and keeps them consistent with other enum flags. No issues here.

Also applies to: 60-61

README.md (2)

105-126: Clear examples of PREFIX and POSTFIX usage.
Including step-by-step code snippets clarifies how to parse JSON embedded within text. This effectively demonstrates the newly added functionality.


174-176: Extended documentation for new flags.
Listing PREFIX and POSTFIX in the Allow enum reference makes it easy for users to discover the new capabilities.

@CNSeniorious000
Copy link
Member

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

@ArmykOliva
Copy link
Author

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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants