Skip to content

Option to create path if "Path not found in document" #46

Open

Description

@bennycode

Given a plain object like this:

{}

If I want to add a property with the path of /compilerOptions/module and the value of nodenext I am expecting the object to be:

{
  "compilerOptions": {
    "module": "nodenext"
  }
}

Unfortunatey, jsonpatch crashes with the message of:

Path not found in document

So I have to split the path and create its parts individually which is quite cumbersome. Can this functionality instead be integrated into this library?

Activity

  1. bennycode commented on Jul 21, 2024

    @bennycode
    ContributorAuthor

    Here is my current workaround with an ensurePaths function:

    import {apply_patch} from 'jsonpatch';
    
    function ensurePaths(json: Record<string, unknown>, pathParts: string[]) {
      let current = json;
      for (let i = 0; i < pathParts.length - 1; i++) {
        const part = pathParts[i];
        if (part) {
          if (!current[part]) {
            current[part] = {};
          }
          current = current[part] as Record<string, unknown>;
        }
      }
    }
    
    export function setJsonValue(json: Record<string, unknown>, jsonPatchPath: string, value: string) {
      const pathParts = jsonPatchPath.split('/').slice(1);
      ensurePaths(json, pathParts);
      try {
        return apply_patch(json, [{op: 'replace', path: jsonPatchPath, value}]);
      } catch (error) {
        // Catch "Replace operation must point to an existing value!"
        return apply_patch(json, [{op: 'add', path: jsonPatchPath, value}]);
      }
    }

    I could improve the error handling if #41 gets implemented.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions