#C8248. Extract Values from JSON by Key

    ID: 52209 Type: Default 1000ms 256MiB

Extract Values from JSON by Key

Extract Values from JSON by Key

You are given a JSON string from standard input. The JSON string contains two fields: json and key. The json field is a JSON object that may include nested objects and arrays, and the key field is the target key for which you have to extract all corresponding values. Your task is to traverse the JSON object recursively and collect all values associated with the given key in a depth-first manner.

For example, consider the JSON string below:

{
    "json": {
        "name": "John",
        "address": {
            "postalCode": "10001",
            "details": {"postalCode": "10002"}
        },
        "postalCode": "10003"
    },
    "key": "postalCode"
}

Your program should output:

["10001", "10002", "10003"]

Note: If there are no occurrences of the key, output an empty JSON array: [].

inputFormat

The input consists of a single JSON string read from standard input. This string contains two fields:

  • json: A JSON object that can contain nested objects or arrays.
  • key: A string representing the key for which you need to extract all values.

The input is guaranteed to be valid JSON.

outputFormat

Output the extracted values as a JSON array of strings to standard output.

## sample
{"json": {"name": "John", "age": 30, "postalCode": "10003"}, "key": "postalCode"}
["10003"]