You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter/Dart中如何提取字符串内嵌套对象的id值

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 the RunHyperlink : prefix, leaving only the curly-brace enclosed data we care about.
  • Fixing JSON validity: The regex (\w+): matches any word-based key (like classid or id) followed by a colon, and replaces it with the quoted version ("classid":). This turns the non-standard string into valid JSON that jsonDecode can process.
  • Extracting the id: Once decoded into a Map<String, dynamic>, we can directly access the id value using the key ['id']. The try-catch block adds a safety net in case the input format ever changes unexpectedly.

内容的提问来源于stack exchange,提问作者JoshuaaMarkk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:59:07