CodeSampleX

샘플

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

검증된 샘플 — npm parse-json 5.2.0: parse valid and invalid JSON with helpful error messages and optional reviver or filename. node 22 · linux alpine/x64 …

sha256:d448c5b2b90458da4c4a3e28851eceed7116c319674afb42dc007fc3e2d42af6

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
parse valid and invalid JSON with helpful error messages and optional reviver or filename
패키지
심벌
  • parseJson
생성일
2026-08-23T15:32:49Z

컨트랙트

  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.

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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/);
}

오리진 시더

익명