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

VB6中如何从类JSON格式字符串提取指定字段值且不转换为JSON

VB6 类JSON字符串字段提取方案

你生成的字符串是固定的"键名":"值"格式,无嵌套、无转义双引号,直接实现通用字段提取函数即可,效率远高于引入JSON解析组件,也支持后续自由扩展字段。

通用提取函数实现

' 入参:源类JSON字符串、要提取的字段名,返回对应字段值
Public Function GetFieldValue(ByVal sourceStr As String, ByVal fieldName As String) As String
    Dim startPos As Long, endPos As Long
    Dim matchTag As String
    ' 构造匹配标识:"fieldName":"
    matchTag = Chr(34) & fieldName & Chr(34) & ":" & Chr(34)
    
    ' 查找字段标识位置
    startPos = InStr(1, sourceStr, matchTag, vbBinaryCompare)
    If startPos = 0 Then
        GetFieldValue = "" ' 无对应字段返回空
        Exit Function
    End If
    
    ' 定位到值的起始位置
    startPos = startPos + Len(matchTag)
    ' 查找值的结束双引号位置
    endPos = InStr(startPos, sourceStr, Chr(34), vbBinaryCompare)
    
    If endPos > startPos Then
        GetFieldValue = Mid(sourceStr, startPos, endPos - startPos)
    Else
        GetFieldValue = ""
    End If
End Function

调用示例

Dim sourceStr As String
Dim code As String, name As String, value As String

' 这里替换为你实际生成/拿到的类JSON字符串
sourceStr = "{" & _
Chr(34) & "code" & Chr(34) & ":" & Chr(34) & "0000001" & Chr(34) & "," & _
Chr(34) & "name" & Chr(34) & ":" & Chr(34) & "product 1" & Chr(34) & "," & _
Chr(34) & "value" & Chr(34) & ":" & Chr(34) & "150.00" & Chr(34) & "}"

' 提取对应字段
code = GetFieldValue(sourceStr, "code")
name = GetFieldValue(sourceStr, "name")
value = GetFieldValue(sourceStr, "value")

' 后续新增字段直接新增调用即可,无需修改函数逻辑,比如:
' Dim productType As String
' productType = GetFieldValue(sourceStr, "type")

注意:你贴的原始拼接代码漏了字段之间的逗号,实际运行生成的字符串格式错误,建议拼接时在字段之间补逗号,避免解析失败。

方案特性

  • 性能极强:仅用VB6原生InStr、Mid字符串函数实现,无额外对象开销,处理超长字符串也不会卡顿
  • 扩展性好:后续新增字段不需要调整核心逻辑,直接传新字段名即可提取
  • 适配你的业务场景:完全匹配你自己生成的字符串规则,不会出现通用JSON解析的兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:27:03