Code Lab

Modo entrevista. Cronômetro de 4 min, sem dicas e sem autocompletar

Safe JSON.parse

FácilErrors4 min

Write a function safeParse(text, fallback). If text is valid JSON, return the parsed value. If the string cannot be parsed, return fallback.

Exemplos

safeParse('{"id":1}', null)

Retorna { id: 1 }

safeParse('{id:1}', null)

Retorna null

In JSON a key must be in double quotes.
safeParse('0', 10)

Retorna 0

`0` is valid JSON too.

Fonte

Carregando o editor...
  1. EntradasafeParse('{"id":1}', null)
    Esperado{ id: 1 }
  2. EntradasafeParse('{id:1}', null)
    Esperadonull
  3. EntradasafeParse('0', 10)
    Esperado0

Os testes ocultos rodam no envio