【问题标题】:is there any way to insert a node at the begin of the JSON file?有没有办法在 JSON 文件的开头插入一个节点?
【发布时间】:2019-03-26 19:44:51
【问题描述】:

有没有办法在 JSON 文件的开头插入一个节点?

jsonArray = JSON.parse(File.open(JSON_filePath).read)
jsonArray << node_to_insert

File.open(JSON_FilePath,"w") do |f|
   f.write(JSON.pretty_generate(jsonArray))
end

脚本插入正常,但在文件末尾,我想像 JSON 文件中的第一条记录一样在开头插入。

【问题讨论】:

    标签: json ruby file insert append


    【解决方案1】:

    使用Array#prepend 代替&lt;&lt;。这将插入/前置而不是追加。

    jsonArray = JSON.parse(File.open(JSON_filePath).read)
    jsonArray.prepend(node_to_insert)
    

    【讨论】:

    • 我们也可以使用:jsonArray.unshift(node_to_insert)
    【解决方案2】:

    要将节点添加到第一个而不是最后一个,为什么不翻转前两行的顺序(稍作改动)?

    jsonArray = [node_to_insert] # initialize to array with your first row
    jsonArray.push( *JSON.parse(File.open(JSON_filePath).read) ) # push results,
                   # use the splat operator (*) to avoid array nesting
    

    【讨论】:

      猜你喜欢
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      相关资源
      最近更新 更多