无需硬编码反序列化外层无标识符的嵌套列表
Got it, let's work through this API response structure problem. It’s super common to run into APIs that return dynamic keys instead of a consistent schema, so here’s how to fix it to get the 'Title' and subcategory list structure you need.
First, let's clarify the raw API response you’re dealing with (I’ll expand your example a bit for clarity):
"email_preferences": [ { "Entertainment/Arts": [ { "value": "Art & exhibitions", "key": "artExhibitions" }, { "value": "Theatre", "key": "theatre" } ] }, { "News/Current Events": [ { "value": "Local news", "key": "localNews" } ] } ]
The issue here is that each category name is used as a dynamic object key, instead of being a dedicated Title field with a separate subcategory array. Here’s how to transform this into the structure you need:
Step-by-Step Transformation
1. Iterate over each category entry
Each item in the email_preferences array is an object with exactly one key (the category title) and its value is the subcategory list.
2. Extract the title and subcategories
For each object, grab the only key to use as your Title field, then map that key’s value to a Subcategories field.
Here’s a practical example in JavaScript (easily adaptable to other languages like Python, Java, etc.):
// Raw API response data const apiResponse = { email_preferences: [ { "Entertainment/Arts": [ { "value": "Art & exhibitions", "key": "artExhibitions" }, { "value": "Theatre", "key": "theatre" } ] }, { "News/Current Events": [ { "value": "Local news", "key": "localNews" } ] } ] }; // Transform to the desired structured format const formattedPreferences = apiResponse.email_preferences.map(categoryObj => { // Get the category title (the only key in the object) const categoryTitle = Object.keys(categoryObj)[0]; return { Title: categoryTitle, Subcategories: categoryObj[categoryTitle] }; }); console.log(formattedPreferences);
Resulting Formatted Data
After running the code above, you’ll get the clean, consistent structure you expected:
[ { "Title": "Entertainment/Arts", "Subcategories": [ { "value": "Art & exhibitions", "key": "artExhibitions" }, { "value": "Theatre", "key": "theatre" } ] }, { "Title": "News/Current Events", "Subcategories": [ { "value": "Local news", "key": "localNews" } ] } ]
Pro Tip for Edge Cases
If there’s any chance the API could return an entry with multiple keys (even if it’s not documented), add a quick guard clause to handle it—like logging a warning and picking the first key, so your code doesn’t break unexpectedly:
const formattedPreferences = apiResponse.email_preferences.map(categoryObj => { const categoryKeys = Object.keys(categoryObj); if (categoryKeys.length > 1) { console.warn(`Unexpected multiple keys in category object: ${categoryKeys.join(', ')}`); } const categoryTitle = categoryKeys[0]; return { Title: categoryTitle, Subcategories: categoryObj[categoryTitle] }; });
内容的提问来源于stack exchange,提问作者Ryan

