写Json文件

时间:2016-07-27 20:34:46

标签: json parsing vbscript

好的,我想要做的是根据与名称匹配的正则表达式覆盖JSON文件中的值。示例JSON内容:

{
"Main": {
    "Modpack": "vanilla",
    "Test1": "Value 1",
    "Test2": "Value 2"
},

"Setup": {
    "Test1": "Value 1",
    "Test2": "Value 2"
},

}

以下是我用来获取值的代码:

Function ParseConfig(File, Key)
  Set objFSO = CreateObject("Scripting.FileSystemObject")
  Set objFile = objFSO.OpenTextFile(File, 1)
  Config = objFile.ReadAll

  Dim oRE
  Dim colMatches
  Dim oMatch, I

  Set oRE = New RegExp
  oRE.Global = True
  oRE.IgnoreCase = False
  oRE.Pattern = """" & Key &""":\s""(.+?)"""
  Set colMatches = oRE.Execute ( Config )

  For Each oMatch In colMatches
    strNextmap = oMatch.SubMatches(0)
  Next

  If strNextmap = "" Or IsNull (strNextmap) Then
    ParseConfig = "ERROR:- Config entry not found!"
  Else
    ParseConfig = strNextmap
  End If
  objFile.Close
End Function

我用以下代码调用该代码:ParseConfig ("config", "Modpack")

如何将该代码修改为...

  1. 打开我传递给它的文件
  2. 找到正确的值。 (我想我可以在这里重复使用我的一些代码)
  3. 替换该值。
  4. 保存文件。

1 个答案:

答案 0 :(得分:0)

好吧,没有得到回复而且顽固真的会推动你不这样做,想出了这个解决方案......

Function WriteConfig ( File, Key, Change )

   ' Read file
   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objFile = objFSO.OpenTextFile( File, 1 )
   Read =   objFile.ReadAll

  ' Find the string
  Set oRE = New Regexp
  oRE.Global = True
  oRE.IgnoreCase = False
  oRE.Pattern = """" & Key &""":\s""(.+?)"""
  Set colMatches = oRE.Execute ( Read )

  For Each oMatch in colMatches
    Match = oMatch.SubMatches(0)
  Next
    Write = Replace ( Read, Match, Change, 1, -1, 0 )

  ' Save the file after modification.
  Set objFile = objFSO.OpenTextFile( File, 2 )
  objFile.Write Write
  objFile.Close

End Function    

我用WriteConfig "config", "Test1", "Value New"

来称呼它

瞧!抓住这个VBScript的东西,我想...... 只是在这里感兴趣的是读取功能。

'  PARSE JSON  ------------------------ '
Function ParseConfig ( File, Key )
' Example: Modpack = ParseConfig ( "config", "Modpack" )

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile( File, 1)
    Config = objFile.ReadAll

    Dim oRE
    Dim colMatches
    Dim oMatch, I

    Set oRE = New Regexp
    oRE.Global = True
    oRE.IgnoreCase = False
    oRE.Pattern = """" & Key &""":\s""(.+?)"""
    Set colMatches = oRE.Execute ( Config )

    For Each oMatch In colMatches
       strNextmap = oMatch.SubMatches(0)
    Next

    If strNextmap = "" Or IsNull (strNextmap) Then
        ParseConfig = "ERROR:- Config entry not found!"
    Else
        ParseConfig = strNextmap
    End If
        objFile.Close
End Function