求助:解析API响应中嵌套在value字段的JSON字符串对象
I’ve run into this exact kind of API quirk before—it’s definitely annoying, but parsing that nested JSON string is totally doable. Let’s break down how to handle it, starting with your example response:
{ "type": "type-A", "value": "{'propA': 'type-A specific element', 'propA2': 'another typeA specific element'}" }
First, a quick note: The inner value string uses single quotes, which is non-standard JSON (JSON requires double quotes). That’s an extra hurdle we’ll need to account for unless the API can be configured to return valid JSON here (if that’s an option, it’s worth asking the API devs—saves you from workarounds!).
Python Solution
In Python, we’ll parse the outer JSON first, then fix the inner string (if needed) and parse it again:
import json import re # Sample API response string api_response = '''{ "type": "type-A", "value": "{'propA': 'type-A specific element', 'propA2': 'another typeA specific element'}" }''' # Fix unescaped single quotes to double quotes (avoids breaking escaped quotes like 'don\'t') fixed_response = re.sub(r"(?<!\\)'", '"', api_response) # Parse the outer JSON object outer_data = json.loads(fixed_response) # Parse the inner JSON string from the 'value' field inner_data = json.loads(outer_data['value']) # Access the inner properties print(inner_data['propA']) # Output: type-A specific element
JavaScript Solution
For JavaScript, the approach is similar—parse the outer JSON, then handle the inner string:
// Sample API response string const apiResponse = `{ "type": "type-A", "value": "{'propA': 'type-A specific element', 'propA2': 'another typeA specific element'}" }`; // Replace unescaped single quotes with double quotes const fixedResponse = apiResponse.replace(/(?<!\\)'/g, '"'); // Parse outer JSON const outerData = JSON.parse(fixedResponse); // Parse inner JSON string const innerData = JSON.parse(outerData.value); // Use the inner data console.log(innerData.propA); // Output: type-A specific element
Java Solution (Using Jackson)
If you’re working with Java and Jackson (a popular JSON library), here’s how to tackle it:
import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; public class NestedJsonParser { public static void main(String[] args) throws Exception { String apiResponse = "{ \"type\": \"type-A\", \"value\": \"{'propA': 'type-A specific element', 'propA2': 'another typeA specific element'}\" }"; // Fix unescaped single quotes to double quotes String fixedResponse = apiResponse.replaceAll("(?<!\\\\)'", "\""); ObjectMapper mapper = new ObjectMapper(); // Parse outer JSON into a generic map Map<String, Object> outerData = mapper.readValue(fixedResponse, Map.class); // Parse the inner JSON string Map<String, Object> innerData = mapper.readValue((String) outerData.get("value"), Map.class); // Access inner properties System.out.println(innerData.get("propA")); // Output: type-A specific element } }
Key Edge Cases to Watch For
- Escaped Quotes: If your
valuestrings contain escaped single quotes (e.g.,'user\'s data'), a simplereplacewill break them. The regex patterns above use negative lookbehind to only replace unescaped single quotes. - Valid Inner JSON: If the API actually returns double quotes in the
valuefield (your example might have used single quotes for clarity), you can skip the quote-replacement step entirely—just parse the outer JSON, then parse thevaluestring directly.
内容的提问来源于stack exchange,提问作者Namoshek

