【问题标题】:AutoHotKey - Replace Multiple Lines in FileAutoHotKey - 替换文件中的多行
【发布时间】:2021-08-01 15:59:42
【问题描述】:

我是 AutoHotkey 的新手,我使用它来将 API JSON 文件从 URL 拉入文件。我已经想出了如何替换单行文本来替换无效的 JSON 对象,但现在我试图在文件中找到一个模式并在将文件解析为 SQL 表之前添加两行。

目前正在寻找以下多行模式:

"AAA": x.xx,   *Note: x.xx is a decimal number that can change per record.*
}

需要在第一行之后添加以下两行:

"BBB" {
  "CCC": NULL

最终结果需要是:

"AAA": x.xx,
"BBB": {
  "CCC": NULL
}

【问题讨论】:

  • 这个 api 是否真的像这样服务于一个损坏的 json?您能否展示一个来自 api 的 json 响应的实际示例?
  • @0x464e 抱歉,stackoverflow 也是新手,尝试插入示例但格式不正确。
  • @0x464e 这是 json 文件的摘录。我已经取出了一些物品。仍在尝试使用stackoverflow。 {"dt":1627322400,"temp":88.63,"feels_like":94.64,"weather":[{"id":803,"main":"Clouds","description":"破云","icon ":"04d"}],"pop":0},{"dt":1627326000,"temp":88.38,"feels_like":93.7,"weather":[{"id":500,"main": "Rain","description":"小雨","icon":"10d"}],"pop":0.4,"rain":{"r1h":0.13}},{"dt":1627329600," temp":87.71,"feels_like":92.84,"weather":[{"id":804,"main":"Clouds","description":"阴云","icon":"04d"}], “流行”:0.08},
  • 我更想知道,如果网站提供的 json 实际上格式无效(就像您的问题似乎暗示的那样),并且您正在尝试修复它,或者 json 是否真的很好。如果没问题,您无需担心匹配模式,只需加载 json 并添加所需的字段即可。
  • 我感觉JSON响应是有效的,可能是你存错了? AHK 可以直接读取 HTTP 响应。

标签: autohotkey


【解决方案1】:

编辑 JSON 文件时,有很多更好的方法可以做到这一点。但是,如果您只想插入一些行,您可以这样做:

oldFile := "original_file.json"
newFile := "edited_file.json"

insertText =
(
"BBB" {
  "CCC": NULL
)

Loop, Read, % oldFile, % newFile
{
    FileAppend, %A_LoopReadLine%`n
    
    ; If last written line is a match, add new lines
    if RegExMatch(A_LoopReadLine, """AAA"": \d+.\d+,")
    {    
        FileAppend, %insertText%`n
    }
}

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2014-02-03
    相关资源
    最近更新 更多