Flutter/Dart中如何提取字符串内嵌套对象的id值
Solution to Extract "id" Value from Non-Standard Hyperlink String
Got it, let's walk through how to grab that id value properly. The problem right now is that the text in splitText[5] isn't valid JSON—all those keys like classid and id don't have double quotes, which means jsonDecode would throw an error if we tried to use it directly. Here's a reliable way to fix this:
Step-by-Step Code Implementation
import 'dart:convert'; // Your existing code to split the text String text = snapshot.data[index]; var splitText = text.split("\n"); // 1. Isolate the hyperlink data part from the line // splitText[5] is "RunHyperlink : {classid: 25510, id: 2, mad_key: 32835}" String hyperlinkContent = splitText[5].split(": ")[1]; // Results in "{classid: 25510, id: 2, mad_key: 32835}" // 2. Convert the non-standard key-value pairs to valid JSON // Use regex to wrap all keys (before colons) in double quotes String validJsonString = hyperlinkContent.replaceAll(RegExp(r'(\w+):'), r'"$1":'); // 3. Decode the JSON and extract the id try { Map<String, dynamic> hyperlinkMap = jsonDecode(validJsonString); int targetId = hyperlinkMap['id']; print(targetId); // Will output: 2 } catch (e) { print("Error parsing hyperlink data: $e"); // Handle any unexpected format issues here }
How This Works
- Isolating the data:
split(": ")[1]cuts off theRunHyperlink :prefix, leaving only the curly-brace enclosed data we care about. - Fixing JSON validity: The regex
(\w+):matches any word-based key (likeclassidorid) followed by a colon, and replaces it with the quoted version ("classid":). This turns the non-standard string into valid JSON thatjsonDecodecan process. - Extracting the id: Once decoded into a
Map<String, dynamic>, we can directly access theidvalue using the key['id']. The try-catch block adds a safety net in case the input format ever changes unexpectedly.
内容的提问来源于stack exchange,提问作者JoshuaaMarkk
相关产品推荐
相关产品推荐

