{"id":"6b093ddebd4755deb67ee077","slug":"json-path-get","title":"Odczyt wartości po ścieżce JSON","summary":"Własna wersja `get(obj, 'orders[1].items[0].sku', default)` – parsowanie prostej ścieżki, rozróżnienie „brak wartości” od `null` i walidacja składni.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":[],"techs":["typescript","javascript","python"],"tags":["parsing","strings","objects","javascript"],"languages":[{"lang":"typescript","runner":"browser","starter":"/**\n * Reads a value by a path like \"orders[1].items[0].sku\".\n * Missing value → defaultValue; invalid syntax → Error('Invalid path: ...').\n */\nfunction getPath(data: unknown, path: string, defaultValue?: unknown): unknown {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":9,"tests":"const DATA = {\n  user: { name: 'Ola', tags: ['admin', 'dev'], manager: null, active: false, score: 0, nick: '' },\n  orders: [{ id: 7 }, { id: 9, items: [{ sku: 'X1' }] }],\n  matrix: [[1, 2], [3, 4]],\n};\n\ntest('nested keys and indices', () => {\n  expect(getPath(DATA, 'user.name')).toBe('Ola');\n  expect(getPath(DATA, 'orders[1].items[0].sku')).toBe('X1');\n  expect(getPath(DATA, 'matrix[1][0]')).toBe(3);\n  expect(getPath(DATA, 'user.tags')).toEqual(['admin', 'dev']);\n});\n\ntest('a path may start with an index', () => {\n  expect(getPath([{ id: 1 }, { id: 2 }], '[1].id')).toBe(2);\n});\n\ntest('missing values give the default', () => {\n  expect(getPath(DATA, 'user.age')).toBeUndefined();\n  expect(getPath(DATA, 'user.age', 18)).toBe(18);\n  expect(getPath(DATA, 'user.tags[5]', 'none')).toBe('none');\n  expect(getPath(DATA, 'user.manager.name', 'none')).toBe('none');\n  expect(getPath(DATA, 'orders[0].items[0].sku', 'none')).toBe('none');\n});\n\ntest('existing falsy values are returned as they are', () => {\n  expect(getPath(DATA, 'user.manager', 'none')).toBeNull();\n  expect(getPath(DATA, 'user.active', true)).toBe(false);\n  expect(getPath(DATA, 'user.score', 10)).toBe(0);\n  expect(getPath(DATA, 'user.nick', 'anon')).toBe('');\n});\n\ntest('keys only on objects, indices only on arrays', () => {\n  expect(getPath(DATA, 'user[0]', 'x')).toBe('x');\n  expect(getPath(DATA, 'orders.id', 'x')).toBe('x');\n  expect(getPath(DATA, 'user.name[0]', 'x')).toBe('x');\n  expect(getPath(DATA, 'user.name.length', 'x')).toBe('x');\n});\n\ntest('inherited properties are not visible', () => {\n  expect(getPath({}, 'toString')).toBeUndefined();\n  expect(getPath({ a: 1 }, 'constructor', 'none')).toBe('none');\n});\n\ntest('empty path returns the data itself', () => {\n  expect(getPath(DATA, '')).toBe(DATA);\n});\n\ntest('invalid syntax throws', () => {\n  for (const bad of ['a..b', '.a', 'a.', 'a[x]', 'a[-1]', 'a[', 'a]', '[]', 'a.[0]']) {\n    expect(() => getPath(DATA, bad)).toThrow('Invalid path');\n  }\n});\n\ntest('performance: a path with 2 000 segments, 2 000 times', () => {\n  let deep = { value: 42 };\n  for (let i = 0; i < 1999; i++) deep = { k: deep };\n  const path = 'k.'.repeat(1999) + 'value';\n  let sum = 0;\n  for (let i = 0; i < 2000; i++) sum += getPath(deep, path);\n  expect(sum).toBe(84000);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Reads a value by a path like \"orders[1].items[0].sku\".\n * Missing value → defaultValue; invalid syntax → Error('Invalid path: ...').\n */\nfunction getPath(data, path, defaultValue) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":9,"tests":"const DATA = {\n  user: { name: 'Ola', tags: ['admin', 'dev'], manager: null, active: false, score: 0, nick: '' },\n  orders: [{ id: 7 }, { id: 9, items: [{ sku: 'X1' }] }],\n  matrix: [[1, 2], [3, 4]],\n};\n\ntest('nested keys and indices', () => {\n  expect(getPath(DATA, 'user.name')).toBe('Ola');\n  expect(getPath(DATA, 'orders[1].items[0].sku')).toBe('X1');\n  expect(getPath(DATA, 'matrix[1][0]')).toBe(3);\n  expect(getPath(DATA, 'user.tags')).toEqual(['admin', 'dev']);\n});\n\ntest('a path may start with an index', () => {\n  expect(getPath([{ id: 1 }, { id: 2 }], '[1].id')).toBe(2);\n});\n\ntest('missing values give the default', () => {\n  expect(getPath(DATA, 'user.age')).toBeUndefined();\n  expect(getPath(DATA, 'user.age', 18)).toBe(18);\n  expect(getPath(DATA, 'user.tags[5]', 'none')).toBe('none');\n  expect(getPath(DATA, 'user.manager.name', 'none')).toBe('none');\n  expect(getPath(DATA, 'orders[0].items[0].sku', 'none')).toBe('none');\n});\n\ntest('existing falsy values are returned as they are', () => {\n  expect(getPath(DATA, 'user.manager', 'none')).toBeNull();\n  expect(getPath(DATA, 'user.active', true)).toBe(false);\n  expect(getPath(DATA, 'user.score', 10)).toBe(0);\n  expect(getPath(DATA, 'user.nick', 'anon')).toBe('');\n});\n\ntest('keys only on objects, indices only on arrays', () => {\n  expect(getPath(DATA, 'user[0]', 'x')).toBe('x');\n  expect(getPath(DATA, 'orders.id', 'x')).toBe('x');\n  expect(getPath(DATA, 'user.name[0]', 'x')).toBe('x');\n  expect(getPath(DATA, 'user.name.length', 'x')).toBe('x');\n});\n\ntest('inherited properties are not visible', () => {\n  expect(getPath({}, 'toString')).toBeUndefined();\n  expect(getPath({ a: 1 }, 'constructor', 'none')).toBe('none');\n});\n\ntest('empty path returns the data itself', () => {\n  expect(getPath(DATA, '')).toBe(DATA);\n});\n\ntest('invalid syntax throws', () => {\n  for (const bad of ['a..b', '.a', 'a.', 'a[x]', 'a[-1]', 'a[', 'a]', '[]', 'a.[0]']) {\n    expect(() => getPath(DATA, bad)).toThrow('Invalid path');\n  }\n});\n\ntest('performance: a path with 2 000 segments, 2 000 times', () => {\n  let deep = { value: 42 };\n  for (let i = 0; i < 1999; i++) deep = { k: deep };\n  const path = 'k.'.repeat(1999) + 'value';\n  let sum = 0;\n  for (let i = 0; i < 2000; i++) sum += getPath(deep, path);\n  expect(sum).toBe(84000);\n});\n"},{"lang":"python","runner":"browser","starter":"def get_path(data, path: str, default=None):\n    \"\"\"Reads a value by a path like \"orders[1].items[0].sku\".\n    Missing value -> default; invalid syntax -> ValueError(\"Invalid path: ...\").\"\"\"\n    raise NotImplementedError\n","testCount":9,"tests":"DATA = {\n    \"user\": {\"name\": \"Ola\", \"tags\": [\"admin\", \"dev\"], \"manager\": None, \"active\": False, \"score\": 0, \"nick\": \"\"},\n    \"orders\": [{\"id\": 7}, {\"id\": 9, \"items\": [{\"sku\": \"X1\"}]}],\n    \"matrix\": [[1, 2], [3, 4]],\n}\n\n\ndef eq(got, expected, what):\n    assert got == expected and type(got) is type(expected), f\"{what}: expected {expected!r}, got {got!r}\"\n\n\ndef test_nested_keys_and_indices():\n    eq(get_path(DATA, \"user.name\"), \"Ola\", \"user.name\")\n    eq(get_path(DATA, \"orders[1].items[0].sku\"), \"X1\", \"orders[1].items[0].sku\")\n    eq(get_path(DATA, \"matrix[1][0]\"), 3, \"matrix[1][0]\")\n    eq(get_path(DATA, \"user.tags\"), [\"admin\", \"dev\"], \"user.tags\")\n\n\ndef test_path_may_start_with_an_index():\n    eq(get_path([{\"id\": 1}, {\"id\": 2}], \"[1].id\"), 2, \"[1].id\")\n\n\ndef test_missing_values_give_the_default():\n    assert get_path(DATA, \"user.age\") is None, \"missing key without a default should give None\"\n    eq(get_path(DATA, \"user.age\", 18), 18, \"user.age with default\")\n    eq(get_path(DATA, \"user.tags[5]\", \"none\"), \"none\", \"index out of range\")\n    eq(get_path(DATA, \"user.manager.name\", \"none\"), \"none\", \"through None\")\n    eq(get_path(DATA, \"orders[0].items[0].sku\", \"none\"), \"none\", \"missing list\")\n\n\ndef test_existing_falsy_values_are_returned():\n    assert get_path(DATA, \"user.manager\", \"none\") is None, \"existing None should be returned, not the default\"\n    eq(get_path(DATA, \"user.active\", True), False, \"user.active\")\n    eq(get_path(DATA, \"user.score\", 10), 0, \"user.score\")\n    eq(get_path(DATA, \"user.nick\", \"anon\"), \"\", \"user.nick\")\n\n\ndef test_keys_only_on_dicts_indices_only_on_lists():\n    eq(get_path(DATA, \"user[0]\", \"x\"), \"x\", \"index on a dict\")\n    eq(get_path(DATA, \"orders.id\", \"x\"), \"x\", \"key on a list\")\n    eq(get_path(DATA, \"user.name[0]\", \"x\"), \"x\", \"index on a string\")\n    eq(get_path(DATA, \"user.name.upper\", \"x\"), \"x\", \"key on a string\")\n\n\ndef test_attributes_are_not_keys():\n    eq(get_path({}, \"__class__\", \"none\"), \"none\", \"__class__\")\n    eq(get_path({\"a\": 1}, \"keys\", \"none\"), \"none\", \"keys\")\n\n\ndef test_empty_path_returns_the_data_itself():\n    assert get_path(DATA, \"\") is DATA, \"empty path should return the same object\"\n\n\ndef test_invalid_syntax_raises():\n    for bad in [\"a..b\", \".a\", \"a.\", \"a[x]\", \"a[-1]\", \"a[\", \"a]\", \"[]\", \"a.[0]\"]:\n        with raises(ValueError, match=\"Invalid path\"):\n            get_path(DATA, bad)\n\n\ndef test_performance_2000_segments():\n    deep = {\"value\": 42}\n    for _ in range(1999):\n        deep = {\"k\": deep}\n    path = \"k.\" * 1999 + \"value\"\n    total = sum(get_path(deep, path) for _ in range(500))\n    eq(total, 21000, \"sum of 500 lookups\")\n"}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:54.384Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Odpowiedzi API bywają głęboko zagnieżdżone, a łańcuchy "},{"type":"text","text":"a && a.b && a.b[0] && …","marks":[{"type":"code"}]},{"type":"text","text":" szybko robią się nieczytelne. Piszemy funkcję, która odczytuje wartość po "},{"type":"text","text":"ścieżce tekstowej","marks":[{"type":"bold"}]},{"type":"text","text":", a gdy czegoś po drodze brakuje, zwraca wartość domyślną."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"getPath(data, path, defaultValue)","marks":[{"type":"code"}]},{"type":"text","text":" (Python: "},{"type":"text","text":"get_path(data, path, default=None)","marks":[{"type":"code"}]},{"type":"text","text":"):"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ścieżka składa się z "},{"type":"text","text":"kluczy","marks":[{"type":"bold"}]},{"type":"text","text":" oddzielonych kropką ("},{"type":"text","text":"user.address.city","marks":[{"type":"code"}]},{"type":"text","text":") i "},{"type":"text","text":"indeksów","marks":[{"type":"bold"}]},{"type":"text","text":" w nawiasach ("},{"type":"text","text":"items[0]","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[2].name","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"matrix[1][0]","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"klucz to niepusty ciąg znaków bez "},{"type":"text","text":".","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"]","marks":[{"type":"code"}]},{"type":"text","text":"; indeks to liczba całkowita ≥ 0 zapisana cyframi,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"klucz odczytujemy tylko z obiektu (słownika), indeks – tylko z tablicy (listy); wszystko inne (napis, liczba, "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"None","marks":[{"type":"code"}]},{"type":"text","text":", zły typ kontenera) oznacza "},{"type":"text","text":"brak","marks":[{"type":"bold"}]},{"type":"text","text":" wartości,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"w JS/TS liczą się tylko "},{"type":"text","text":"własne","marks":[{"type":"bold"}]},{"type":"text","text":" właściwości obiektu ("},{"type":"text","text":"toString","marks":[{"type":"code"}]},{"type":"text","text":" czy "},{"type":"text","text":"constructor","marks":[{"type":"code"}]},{"type":"text","text":" z prototypu to brak wartości),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"brak wartości gdziekolwiek po drodze → zwracamy "},{"type":"text","text":"defaultValue","marks":[{"type":"code"}]},{"type":"text","text":" (domyślnie "},{"type":"text","text":"undefined","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"None","marks":[{"type":"code"}]},{"type":"text","text":"),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"wartość, która "},{"type":"text","text":"istnieje","marks":[{"type":"bold"}]},{"type":"text","text":", zwracamy nawet wtedy, gdy jest "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"0","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"false","marks":[{"type":"code"}]},{"type":"text","text":" albo pustym napisem,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"pusta ścieżka zwraca "},{"type":"text","text":"data","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"niepoprawna składnia ("},{"type":"text","text":"a..b","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":".a","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a.","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a[x]","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a[-1]","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a[","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a]","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"[]","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"a.[0]","marks":[{"type":"code"}]},{"type":"text","text":") → "},{"type":"text","text":"Error","marks":[{"type":"code"}]},{"type":"text","text":" / "},{"type":"text","text":"ValueError","marks":[{"type":"code"}]},{"type":"text","text":" z komunikatem zawierającym "},{"type":"text","text":"Invalid path","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"przyklady"},"content":[{"type":"text","text":"Przykłady"}]},{"type":"paragraph","content":[{"type":"text","text":"Dla "},{"type":"text","text":"data = { user: { name: 'Ola', tags: ['admin', 'dev'], manager: null }, orders: [{ id: 7 }, { id: 9, items: [{ sku: 'X1' }] }] }","marks":[{"type":"code"}]},{"type":"text","text":":"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"path","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"defaultValue","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wynik"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"user.name\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"–"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"Ola\"","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"orders[1].items[0].sku\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"–"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"X1\"","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"user.tags[5]\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"none\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"none\"","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"user.manager\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"none\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":" – wartość istnieje"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"user.manager.name\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"none\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"none\"","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"user..name\"","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"–"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wyjątek "},{"type":"text","text":"Invalid path","marks":[{"type":"code"}]}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Ścieżki do 2 000 segmentów, dane w stylu JSON (obiekty/słowniki, tablice/listy, napisy, liczby, wartości logiczne, "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Czas "},{"type":"text","text":"O(p)","marks":[{"type":"bold"}]},{"type":"text","text":", gdzie "},{"type":"text","text":"p","marks":[{"type":"code"}]},{"type":"text","text":" – długość ścieżki; pamięć "},{"type":"text","text":"O(p)","marks":[{"type":"bold"}]},{"type":"text","text":" na segmenty."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[],"topicsInfo":[],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:54.386Z","updatedAt":"2026-11-27T08:22:54.386Z"}