Using VBScript to find and replace all multi-line text between curly braces of a node within a JSON file

前端 未结 1 1890
面向向阳花
面向向阳花 2020-12-20 03:15

As part of a Windows logon script (hence the VBScript requirement), I would like to set values in a user\'s Google Chrome preferences (stored in a JSON file in the user prof

相关标签:
1条回答
  • 2020-12-20 03:51

    You can do the replacement with a regular expression:

    prefsFile = "%userprofile%\Local Settings\...\Preferences"
    prefsFile = CreateObject("WScript.Shell").ExpandEnvironmentStrings(prefsFile)
    
    newPrefs = "..."
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    json = fso.OpenTextFile(prefsFile).ReadAll
    
    Set re = New RegExp
    re.Pattern = """download"": {[\s\S]*?},"
    
    json = re.Replace(json, """download"": {" & vbCrLf & newPrefs & vbCrLf & "},")
    
    fso.OpenTextFile(prefsFile, 2).Write(json)
    

    The pattern [\s\S] matches any whitespace or non-whitespace character. You can't use . in this case, because that special character does not match newlines, and you want the expression to span multiple lines. The qualifiers * and ? mean "match any number of characters" and "use the shortest match" respectively. That way the expression matches everything between a pair of curly braces after the "download": keyword.

    0 讨论(0)
提交回复
热议问题