All challenges
Easy 0 solved 0% acceptance

Build a JSON Object

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

What you'll learn

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

Problem

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

Constraints

0 ≤ number of pairs ≤ 100

Keys and values have at most 50 printable characters

Examples

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

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

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

Expected output:
string expected = "{\"name\": \"Ada\", \"city\": \"London\"}";

Explanation

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

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

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

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

Expected output:
string expected = "{\"quote\": \"say \\\"hi\\\"\"}";

Explanation

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

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

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

Hint 3

An empty input still needs the braces: {}.

Expected complexity

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

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.