如何从指定JSON源提取并过滤键生成数组型输出?
How to Convert Your JSON Pages to a Filtered Array
If you need to transform your input JSON into the desired array format—including filtering entries where the key starts with yomama—here's a straightforward approach using JavaScript (one of the most common languages for JSON manipulation):
Step-by-Step Explanation
The core tasks are:
- Iterate over the keys in the
pagesobject - Filter out entries that don't start with
yomama - Reshape each remaining entry to include the key as a
urlproperty alongsidedataandorder
JavaScript Implementation
const input = { "pages":{ "yomama/first key": { "data": { "fieldset": "lesson-video-overview", "title": "5th Grade Math - Interpreting Fractions", }, "order": 4 }, "yomama/second key": { "data": { "fieldset": "lesson-video-clip-single", "title": "Post-Lesson Debrief Part 5", }, "order": 14 }, "yopapa/Third key": { "data": { "fieldset": "lesson-video-clip-single", "title": "Lesson Part 2B", }, "order": 6 } } }; // Transform and filter entries const filteredArray = Object.entries(input.pages) // Keep only keys starting with "yomama" .filter(([key]) => key.startsWith('yomama')) // Reshape each entry to the desired structure .map(([url, { data, order }]) => ({ url, data, order })); console.log(filteredArray);
Output
[ { "url": "yomama/first key", "data": { "fieldset": "lesson-video-overview", "title": "5th Grade Math - Interpreting Fractions" }, "order": 4 }, { "url": "yomama/second key", "data": { "fieldset": "lesson-video-clip-single", "title": "Post-Lesson Debrief Part 5" }, "order": 14 } ]
Key Details
- Filtering: The
filtermethod checks if each key starts withyomama. If you want to include all entries (includingyopapa), just remove this line. - Destructuring: We use array destructuring to get the key (renamed to
url) and object destructuring to extractdataandorderfrom each entry. - Case Sensitivity: If you need case-insensitive matching (e.g.,
Yomama/...should also be included), modify the filter tokey.toLowerCase().startsWith('yomama').
Python Alternative
If you prefer Python, here's an equivalent implementation:
import json # Load the input JSON input_data = json.loads(''' { "pages":{ "yomama/first key": { "data": { "fieldset": "lesson-video-overview", "title": "5th Grade Math - Interpreting Fractions" }, "order": 4 }, "yomama/second key": { "data": { "fieldset": "lesson-video-clip-single", "title": "Post-Lesson Debrief Part 5" }, "order": 14 }, "yopapa/Third key": { "data": { "fieldset": "lesson-video-clip-single", "title": "Lesson Part 2B" }, "order": 6 } } } ''') result = [] for url, entry in input_data['pages'].items(): # Filter entries starting with "yomama" if url.startswith('yomama'): result.append({ 'url': url, 'data': entry['data'], 'order': entry['order'] }) # Print the formatted result print(json.dumps(result, indent=2))
This will produce the same filtered array as the JavaScript version.
内容的提问来源于stack exchange,提问作者Selwyn Polit
相关产品推荐
相关产品推荐

