簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。