jq对象数组转对象:curl响应ID重映射与结构转换需求
Solution: Transform Response Data with ID Mapping & Array-to-Object Conversion
Got it, let's sort this out for you! Transforming that response data to map IDs and switch from an array to a key-value object is totally doable—here's how to pull it off in two common languages:
JavaScript (Frontend/Node.js)
First, let's define your input data and ID mapping, then run the transformation:
// Your raw curl response data const responseData = [ { "list": [ { "value": 1, "id": 12 }, { "value": 15, "id": 13 }, { "value": -4, "id": 14 } ] }, // Add other objects from your response here... ]; // Your ID-to-newID mapping const idMap = { "12": "newId1", "13": "newId2", "14": "newId3" }; // Transform the data const transformedData = responseData.map(item => { // Convert the list array to a key-value object using reduce const mappedList = item.list.reduce((acc, currentEntry) => { // Convert the numeric ID to a string to match the map's keys const newId = idMap[currentEntry.id.toString()]; // Only add entries that have a valid mapping if (newId) { acc[newId] = currentEntry.value; } return acc; }, {}); return { list: mappedList }; }); // Check the result console.log(transformedData);
How this works:
map()loops through every top-level object in your response arrayreduce()builds a new object from the originallistarray, using the mapped ID as the key and the entry'svalueas the value- We convert the numeric
idto a string to ensure it matches the string keys in youridMap(this is a common gotcha!)
Python (Backend Scripting)
If you're working with Python to process the response, here's an equivalent solution:
import json # Your raw response data (parsed from curl output) response_data = [ {"list": [{"value": 1, "id": 12}, {"value": 15, "id": 13}, {"value": -4, "id": 14}]}, # Add other objects here... ] # Your ID mapping id_map = {"12": "newId1", "13": "newId2", "14": "newId3"} transformed_data = [] for item in response_data: mapped_list = {} for entry in item["list"]: # Convert numeric ID to string to match the map new_id = id_map.get(str(entry["id"])) if new_id: mapped_list[new_id] = entry["value"] transformed_data.append({"list": mapped_list}) # Print the formatted result print(json.dumps(transformed_data, indent=2))
Key notes for Python:
- We use a nested loop to iterate through each top-level object and its
listentries id_map.get()safely checks for a matching ID (avoids errors if an ID isn't in the map)json.dumps()prints the result in a readable JSON format
Either of these solutions will output exactly the structure you need:
[ { "list": { "newId1": 1, "newId2": 15, "newId3": -4 } }, ... ]
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

