Torna alle sfide
Facile 0 risolte 0% di accettazione

Build a JSON Object

Turn keys and values into a JSON object string, escaping quotes and backslashes correctly.

Cosa imparerai

  • Write key-value pairs in JSON syntax
  • Escape quotes and backslashes inside strings
  • Join parts with a separator

Problema

Mostra traduzione

JSON is the text format most programs use to exchange data. A JSON object is written as {"key": "value", ...}.

Given matching lists of keys and values (all text), build the JSON object string in this exact format:

  • Start with { and end with }.
  • Write each pair as "key": "value", in the given order, separated by , (comma and space).
  • Inside a string, write a backslash \ as \\ and a double quote " as \". Other characters stay as they are.

Implement json_object_string(keys, values).

Input

keys, values: Lists of the same length.

Output

Return the JSON text. An empty object is {}.

Vincoli

0 ≤ number of pairs ≤ 100

Keys and values have at most 50 printable characters

Esempi

Esempio 1
Input:
keys = ["name", "city"]
values = ["Ada", "London"]

Output atteso:
expected = "{\"name\": \"Ada\", \"city\": \"London\"}"
Input:
std::vector<std::string> keys = {"name", "city"};
std::vector<std::string> values = {"Ada", "London"};

Output atteso:
std::string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
Input:
string[] keys = new string[] {"name", "city"};
string[] values = new string[] {"Ada", "London"};

Output atteso:
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";

Spiegazione

Each pair becomes "key": "value": {"name": "Ada", "city": "London"}.

Esempio 2
Input:
keys = ["quote"]
values = ["say \"hi\""]

Output atteso:
expected = "{\"quote\": \"say \\\"hi\\\"\"}"
Input:
std::vector<std::string> keys = {"quote"};
std::vector<std::string> values = {"say \"hi\""};

Output atteso:
std::string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
Input:
string[] keys = new string[] {"quote"};
string[] values = new string[] {"say \"hi\""};

Output atteso:
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";

Spiegazione

The quotes inside the value are escaped with a backslash: {"quote": "say \"hi\""}.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Build each "key": "value" pair separately, then join them.

Suggerimento 2

Escape backslashes before quotes so you don't escape your own escapes.

Suggerimento 3

An empty input still needs the braces: {}.

Complessità attesa

O(total length) time, O(total length) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.