A small Symfony console utility to extract key + value pairs from a JSON file and write them to a new JSON file.
This project provides a single command: app:extract-json.
- PHP >= 8.2
- Composer dependencies installed (
composer install)
- Clone the repository
- Install dependencies:
composer install
Run the command via Symfony Console:
php bin/console app:extract-json <file> <key> <value> [--output|-o <path>] [--pretty] [-v|-vv|-vvv]file(argument, required): Path to the input JSON file.key(argument, required): Field name to use as the "key" in output.value(argument, required): Field name to use as the "value" in output.--output, -o(option, optional): Path to write the output JSON file. Defaults to<input>.extracted.json(appended to the input filename).--pretty(option, flag): Pretty-print the output JSON.-v|-vv|-vvv(verbosity): Show warnings for skipped items at verbose levels.
- The input JSON must be an array of objects (or associative arrays).
- Each item should contain both the provided
keyandvaluefields. - Items missing either field, or non-object items, are skipped (warnings shown at
-vverbosity).
The output is a single JSON object mapping the provided key to the provided value:
{
"<key>": "<value>"
}0on success1on failure (e.g., unreadable/missing input file, invalid JSON, failed write)
Given people.json:
[
{ "id": 1, "name": "Alice", "other": true },
{ "id": 2, "name": "Bob" },
{ "id": 3 }
]Extract id and name into a new JSON file (pretty-printed):
php bin/console app:extract-json people.json id name --pretty
# Writes people.json.extracted.json in the same directoryWrite to a specific output path and show verbose warnings for skipped items:
php bin/console app:extract-json people.json id name -o build/ids-and-names.json -vResulting output (pretty-printed):
{
"1": "Alice",
"2": "Bob"
}Run tests:
vendor/bin/phpunit- The command attempts to create the output directory if it does not exist.
- The input file path supports tilde (~) expansion (e.g.,
~/Downloads/file.json). - If duplicate keys are encountered, the last occurrence wins (later items overwrite earlier ones).
- Non‑UTF8 characters are preserved; when
--prettyis used, slashes and Unicode are not escaped.