如何将单个JSON及多JSON格式字符串转换为指定键值对列表?
Got it, let's break down your two JSON transformation needs with clear, actionable code examples in Python and JavaScript—since those are the go-to languages for these tasks:
If your "single JSON" refers to a standard JSON object (a collection of key-value pairs), the solution is straightforward: we just need to extract each key-value pair from the object and format them into a list. Here's how to do it in two popular languages:
Python Example
import json # Sample single JSON string single_json_str = '{"name": "Alice", "age": 30, "city": "New York"}' # Step 1: Parse the JSON string into a Python dictionary json_obj = json.loads(single_json_str) # Option 1: Get a list of (key, value) tuples key_value_tuples = list(json_obj.items()) print(key_value_tuples) # Output: [('name', 'Alice'), ('age', 30), ('city', 'New York')] # Option 2: Format into a list of {"Key": key, "Value": value} dictionaries formatted_key_value_list = [{"Key": k, "Value": v} for k, v in json_obj.items()] print(formatted_key_value_list) # Output: [{'Key': 'name', 'Value': 'Alice'}, {'Key': 'age', 'Value': 30}, {'Key': 'city', 'Value': 'New York'}]
JavaScript Example
// Sample single JSON string const singleJsonStr = '{"name": "Alice", "age": 30, "city": "New York"}'; // Step 1: Parse the JSON string into a JavaScript object const jsonObj = JSON.parse(singleJsonStr); // Option 1: Get an array of [key, value] pairs const keyValuePairs = Object.entries(jsonObj); console.log(keyValuePairs); // Output: [['name', 'Alice'], ['age', 30], ['city', 'New York']] // Option 2: Format into an array of {Key: key, Value: value} objects const formattedKeyValueArray = keyValuePairs.map(([key, value]) => ({ Key: key, Value: value })); console.log(formattedKeyValueArray); // Output: [{Key: 'name', Value: 'Alice'}, {Key: 'age', Value: 30}, {Key: 'city', Value: 'New York'}]
This one is trickier because JSON objects themselves contain commas—so splitting the entire string by commas will break the JSON structure. Instead, we need to manually parse the string by matching IDs and their corresponding full JSON objects (using bracket counting to handle nested JSON if needed).
Python Example
import json # Sample input string input_str = '101,{"name": "Alice", "age": 30}, 102,{"city": "London", "job": "Engineer"}, 103,{"hobby": "Reading"}' def parse_id_json_string(input_string): result = [] index = 0 str_length = len(input_string) while index < str_length: # Skip any leading whitespace while index < str_length and input_string[index].isspace(): index += 1 # Extract the ID (from current position to the next comma) id_end = input_string.find(',', index) if id_end == -1: break # End of string, no more entries current_id = input_string[index:id_end].strip() index = id_end + 1 # Move past the comma # Skip whitespace after the comma while index < str_length and input_string[index].isspace(): index += 1 # Check if we're at the start of a JSON object if input_string[index] != '{': # Invalid format—skip to next comma and continue index = input_string.find(',', index) + 1 or str_length continue # Find the closing bracket of the JSON object (handles nested objects too) bracket_count = 1 json_end = index + 1 while json_end < str_length and bracket_count > 0: if input_string[json_end] == '{': bracket_count += 1 elif input_string[json_end] == '}': bracket_count -= 1 json_end += 1 # Parse the JSON string into an object json_str = input_string[index:json_end] try: json_obj = json.loads(json_str) result.append({"Key": current_id, "Value": json_obj}) except json.JSONDecodeError: # Skip invalid JSON entries pass index = json_end # Move past the closing bracket return result # Get the final list output_list = parse_id_json_string(input_str) print(output_list) # Output: # [ # {'Key': '101', 'Value': {'name': 'Alice', 'age': 30}}, # {'Key': '102', 'Value': {'city': 'London', 'job': 'Engineer'}}, # {'Key': '103', 'Value': {'hobby': 'Reading'}} # ]
JavaScript Example
const inputStr = '101,{"name": "Alice", "age": 30}, 102,{"city": "London", "job": "Engineer"}, 103,{"hobby": "Reading"}'; function parseIdJsonString(inputString) { const result = []; let index = 0; const strLength = inputString.length; while (index < strLength) { // Skip leading whitespace while (index < strLength && inputString[index].trim() === '') index++; // Extract the ID const idEnd = inputString.indexOf(',', index); if (idEnd === -1) break; const currentId = inputString.slice(index, idEnd).trim(); index = idEnd + 1; // Skip whitespace after comma while (index < strLength && inputString[index].trim() === '') index++; // Check for valid JSON start if (inputString[index] !== '{') { // Skip to next comma index = inputString.indexOf(',', index) + 1 || strLength; continue; } // Find closing bracket (handles nested JSON) let bracketCount = 1; let jsonEnd = index + 1; while (jsonEnd < strLength && bracketCount > 0) { if (inputString[jsonEnd] === '{') bracketCount++; else if (inputString[jsonEnd] === '}') bracketCount--; jsonEnd++; } // Parse JSON and add to result const jsonStr = inputString.slice(index, jsonEnd); try { const jsonObj = JSON.parse(jsonStr); result.push({ Key: currentId, Value: jsonObj }); } catch (err) { // Skip invalid entries } index = jsonEnd; } return result; } // Get the final array const outputArray = parseIdJsonString(inputStr); console.log(outputArray); // Output: // [ // { Key: '101', Value: { name: 'Alice', age: 30 } }, // { Key: '102', Value: { city: 'London', job: 'Engineer' } }, // { Key: '103', Value: { hobby: 'Reading' } } // ]
内容的提问来源于stack exchange,提问作者saraswathi

