Retour aux défis
Facile 0 résolus 0 % de réussite

Build a JSON Object

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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

Contraintes

0 ≤ number of pairs ≤ 100

Keys and values have at most 50 printable characters

Exemples

Exemple 1
Entrée :
keys = ["name", "city"]
values = ["Ada", "London"]

Sortie attendue :
expected = "{\"name\": \"Ada\", \"city\": \"London\"}"
Entrée :
std::vector<std::string> keys = {"name", "city"};
std::vector<std::string> values = {"Ada", "London"};

Sortie attendue :
std::string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";
Entrée :
string[] keys = new string[] {"name", "city"};
string[] values = new string[] {"Ada", "London"};

Sortie attendue :
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";

Explication

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

Exemple 2
Entrée :
keys = ["quote"]
values = ["say \"hi\""]

Sortie attendue :
expected = "{\"quote\": \"say \\\"hi\\\"\"}"
Entrée :
std::vector<std::string> keys = {"quote"};
std::vector<std::string> values = {"say \"hi\""};

Sortie attendue :
std::string expected = "{\"quote\": \"say \\\"hi\\\"\"}";
Entrée :
string[] keys = new string[] {"quote"};
string[] values = new string[] {"say \"hi\""};

Sortie attendue :
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

An empty input still needs the braces: {}.

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.