Легко Решено: 0 Процент решений: 0%

Build a JSON Object

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

Чему вы научитесь

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

Условие

Показать перевод

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 {}.

Ограничения

0 ≤ number of pairs ≤ 100

Keys and values have at most 50 printable characters

Примеры

Пример 1
Ввод:
keys = ["name", "city"]
values = ["Ada", "London"]

Ожидаемый вывод:
expected = "{\"name\": \"Ada\", \"city\": \"London\"}"
Ввод:
std::vector<std::string> keys = {"name", "city"};
std::vector<std::string> values = {"Ada", "London"};

Ожидаемый вывод:
std::string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
Ввод:
string[] keys = new string[] {"name", "city"};
string[] values = new string[] {"Ada", "London"};

Ожидаемый вывод:
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";

Пояснение

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

Пример 2
Ввод:
keys = ["quote"]
values = ["say \"hi\""]

Ожидаемый вывод:
expected = "{\"quote\": \"say \\\"hi\\\"\"}"
Ввод:
std::vector<std::string> keys = {"quote"};
std::vector<std::string> values = {"say \"hi\""};

Ожидаемый вывод:
std::string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
Ввод:
string[] keys = new string[] {"quote"};
string[] values = new string[] {"say \"hi\""};

Ожидаемый вывод:
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";

Пояснение

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

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

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

Подсказка 2

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

Подсказка 3

An empty input still needs the braces: {}.

Ожидаемая сложность

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

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.