A data analyst needs to extract data from an API that returns JSON. The analyst wants to convert the JSON output into a tabular format for analysis. Which function in a scripting language is commonly used for this purpose?
Trap 1: json.loads()
json.loads() parses a JSON string into Python dictionaries and lists; it performs no tabular conversion, so the analyst still needs pandas.json_normalize or DataFrame construction. It is tempting because it is the standard first step when reading API responses, and would be correct if the goal were merely to deserialise JSON.
Trap 2: to_csv()
to_csv() writes an existing DataFrame or Series out to a CSV file; it cannot parse a JSON API response into tabular rows. It is tempting because CSV is the desired end format, and it would be correct once the data has already been loaded into a DataFrame and needs exporting.
Trap 3: read_json()
read_json() reads JSON from a file path, URL or buffer into a DataFrame, but the stem supplies an API response object rather than a file, and pandas.json_normalize is the function for flattening nested JSON records into columns. read_json() would be correct when the JSON already exists as a file.
- A
json.loads()
Why it fails: json.loads() parses a JSON string into Python dictionaries and lists; it performs no tabular conversion, so the analyst still needs pandas.json_normalize or DataFrame construction. It is tempting because it is the standard first step when reading API responses, and would be correct if the goal were merely to deserialise JSON.
- B
to_csv()
Why it fails: to_csv() writes an existing DataFrame or Series out to a CSV file; it cannot parse a JSON API response into tabular rows. It is tempting because CSV is the desired end format, and it would be correct once the data has already been loaded into a DataFrame and needs exporting.
- C
read_json()
Why it fails: read_json() reads JSON from a file path, URL or buffer into a DataFrame, but the stem supplies an API response object rather than a file, and pandas.json_normalize is the function for flattening nested JSON records into columns. read_json() would be correct when the JSON already exists as a file.
- D
json_normalize()
json_normalize() flattens nested JSON objects and arrays into a flat table, producing the tabular structure the analyst needs. It satisfies the stem's conversion requirement directly, unlike parsing or serialisation functions that merely read or write JSON.