CodeSampleX

Exemplo

parse-json 5.2.0: parse valid and invalid JSON with helpful error messages and optional reviver or filename

Amostra verificada para npm parse-json 5.2.0: parse valid and invalid JSON with helpful error messages and optional reviver or filename. O contrato rodou em…

sha256:d448c5b2b90458da4c4a3e28851eceed7116c319674afb42dc007fc3e2d42af6

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-23

Caso

HOW
Objetivo
parse valid and invalid JSON with helpful error messages and optional reviver or filename
Pacotes
Símbolos
  • parseJson
Criado
2026-08-23T15:32:49Z

Contrato

  1. Parsing valid JSON returns the parsed JavaScript value.
  2. Parsing valid JSON with a custom reviver function transforms values according to the reviver.
  3. Passing a filename string as the second argument parses valid JSON successfully.
  4. Passing both reviver and filename arguments parses valid JSON successfully.
  5. Parsing invalid JSON throws an instance of parseJson.JSONError.
  6. Passing a filename as the second argument attaches fileName and appends 'in <filename>' to the error message.
  7. Passing reviver and filename attaches fileName and appends 'in <filename>' to the error message.
  8. Mutating the fileName property on a caught JSONError updates the fileName property and the formatted error message.

Arquivos

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# parse-json Error Handling, Reviver, and Filename Support

## Search Results and Prior Findings

A search for prior solutions on `pkg:npm/parse-json@5.2.0` returned `NO_SAFE_MATCH`. This sample establishes verified behavior for the `parseJson` symbol family and error semantics.

## Pinned Release

- `parse-json`: `5.2.0`

## Observed Behavior

1. **Valid JSON Parsing**: `parseJson(string)` parses valid JSON strings into JavaScript objects or primitive values identical to `JSON.parse`.
2. **Reviver Function**: When passed a function as the second argument, `parseJson(string, reviver)` transforms values during parsing according to the reviver specification.
3. **Filename Argument**: When passed a string as the second argument (or third argument when reviver is supplied), `parseJson` treats it as the filename associated with the parsed source.
4. **JSONError on Syntax Error**: When parsing invalid JSON, `parseJson` throws an instance of `parseJson.JSONError` (which extends `Error`).
5. **Filename in Error Message**: When a filename is provided, the thrown `JSONError` has its `fileName` property populated and appends `in <filename>` to its error message.
6. **Dynamic Filename Assignment**: Mutating the `fileName` property on a caught `JSONError` instance dynamically updates the formatted error message.

## Failure Modes

- Relying on native `SyntaxError` checks rather than `parseJson.JSONError` can cause missed type narrowing when inspecting error details.
- Expecting a code frame to always match regex across arbitrary V8 runtime versions without checking for standard `JSONError` properties.
csx.json
{"case":{"caseId":"case:sha256:1a8c47437102e4c2fbc8e1cfcc6cf5d1e44a01f22b98c665dd739228e55da0b6","contract":["Parsing valid JSON returns the parsed JavaScript value.","Parsing valid JSON with a custom reviver function transforms values according to the reviver.","Passing a filename string as the second argument parses valid JSON successfully.","Passing both reviver and filename arguments parses valid JSON successfully.","Parsing invalid JSON throws an instance of parseJson.JSONError.","Passing a filename as the second argument attaches fileName and appends 'in \u003cfilename\u003e' to the error message.","Passing reviver and filename attaches fileName and appends 'in \u003cfilename\u003e' to the error message.","Mutating the fileName property on a caught JSONError updates the fileName property and the formatted error message."],"goal":"parse valid and invalid JSON with helpful error messages and optional reviver or filename","kind":"HOW","packages":["pkg:npm/parse-json@5.2.0"],"schemaVersion":1,"symbols":["parseJson"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/parse-json@5.2.0"],"schemaVersion":1,"subject":"pkg:npm/parse-json@5.2.0","symbols":["parseJson"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "parse-json-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "parse-json-sample",
      "version": "1.0.0",
      "dependencies": {
        "parse-json": "5.2.0"
      }
    },
    "node_modules/@babel/code-frame": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
      "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
      "license": "MIT",
      "dependencies": {
        "@babel/helper-validator-identifier": "^7.29.7",
        "js-tokens": "^4.0.0",
        "picocolors": "^1.1.1"
      },
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/@babel/helper-validator-identifier": {
      "version": "7.29.7",
      "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
      "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    },
    "node_modules/error-ex": {
      "version": "1.3.4",
      "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",
      "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==",
      "license": "MIT",
      "dependencies": {
        "is-arrayish": "^0.2.1"
      }
    },
    "node_modules/is-arrayish": {
      "version": "0.2.1",
      "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
      "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
      "license": "MIT"
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/json-parse-even-better-errors": {
      "version": "2.3.1",
      "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
      "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
      "license": "MIT"
    },
    "node_modules/lines-and-columns": {
      "version": "1.2.4",
      "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
      "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
      "license": "MIT"
    },
    "node_modules/parse-json": {
      "version": "5.2.0",
      "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
      "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",
      "license": "MIT",
      "dependencies": {
        "@babel/code-frame": "^7.0.0",
        "error-ex": "^1.3.1",
        "json-parse-even-better-errors": "^2.3.0",
        "lines-and-columns": "^1.1.6"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/sponsors/sindresorhus"
      }
    },
    "node_modules/picocolors": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
      "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
      "license": "ISC"
    }
  }
}
package.json
{
  "name": "parse-json-sample",
  "version": "1.0.0",
  "description": "Demonstrate parse-json error handling and options",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "parse-json": "5.2.0"
  }
}
test/contract.mjs
import parseJson from 'parse-json';
import assert from 'node:assert/strict';

// 1. Parsing valid JSON returns the parsed JavaScript value
const validObj = parseJson('{"name": "csx", "count": 42}');
assert.deepEqual(validObj, { name: 'csx', count: 42 });

// 2. Parsing valid JSON with a custom reviver function transforms values
const revivedObj = parseJson('{"count": 21}', (key, value) => {
  if (typeof value === 'number') {
    return value * 2;
  }
  return value;
});
assert.equal(revivedObj.count, 42);

// 3. Passing a filename as the second argument parses valid JSON successfully
const validWithFile = parseJson('{"enabled": true}', 'config.json');
assert.deepEqual(validWithFile, { enabled: true });

// 4. Passing reviver and filename arguments parses valid JSON successfully
const validWithBoth = parseJson(
  '{"score": 10}',
  (key, value) => (typeof value === 'number' ? value * 3 : value),
  'scores.json'
);
assert.deepEqual(validWithBoth, { score: 30 });

// 5. Parsing invalid JSON throws parseJson.JSONError
const invalidJson = '{\n  "key": "value",\n}';
assert.throws(
  () => {
    parseJson(invalidJson);
  },
  (err) => {
    assert.ok(err instanceof parseJson.JSONError, 'Error should be an instance of parseJson.JSONError');
    assert.ok(err instanceof Error, 'Error should be an instance of Error');
    assert.equal(err.name, 'JSONError');
    assert.match(err.message, /while parsing/);
    return true;
  }
);

// 6. Passing a filename as the second argument attaches fileName and includes it in error message
assert.throws(
  () => {
    parseJson(invalidJson, 'settings.json');
  },
  (err) => {
    assert.ok(err instanceof parseJson.JSONError);
    assert.equal(err.fileName, 'settings.json');
    assert.match(err.message, /in settings\.json/);
    return true;
  }
);

// 7. Passing reviver and filename attaches fileName and includes it in error message
assert.throws(
  () => {
    parseJson(
      invalidJson,
      (key, value) => value,
      'app.json'
    );
  },
  (err) => {
    assert.ok(err instanceof parseJson.JSONError);
    assert.equal(err.fileName, 'app.json');
    assert.match(err.message, /in app\.json/);
    return true;
  }
);

// 8. Mutating fileName property on caught JSONError updates error message with filename
try {
  parseJson(invalidJson);
} catch (err) {
  assert.ok(err instanceof parseJson.JSONError);
  assert.equal(err.fileName, undefined);
  err.fileName = 'dynamic.json';
  assert.equal(err.fileName, 'dynamic.json');
  assert.match(err.message, /in dynamic\.json/);
}

Seeder de origem

anônimo