2016-07-27 29 views
0

これで、JSONファイルの値を正規表現に基づいて上書きすることができます。例JSONコンテンツ:Jsonファイルを書き込む

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 

私はそのコードを呼び出す:

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

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

} 

そして、ここで私は値を取得するために使用していたコードであるParseConfig ("config", "Modpack")

どのように私はhellipを、&するために、そのコードを変更します。

  1. オープン私は
  2. 正しい値を見つけを書くためにそれに渡すファイル。 (ここで私のコードを再利用できると仮定します)
  3. その値を置き換えます。
  4. ファイルを保存します。
+0

JSONは[type-2 grammar](https://en.wikipedia.org/wiki/Chomsky_hierarchy)です。正規表現(type-3文法)では解析できません。それには実際のパーサが必要です。 –

+0

フォーマットは "name": "value"なので、値を取得します。 私はそれが必要でした。 – Bolte

答えて

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のもののハングアップを取得... ちょうどここに誰かが興味を持っているincase読み取り機能です。

' 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 
関連する問題