开发者

Getting a Ruby Array of objects (from nokogiri) into JSON

开发者 https://www.devze.com 2023-02-14 16:12 出处:网络
I have an array of anchor tags returned by nokogiri that I need to coerce into a hash of values in order to output them as JSON. In that process I need to add some key/value pairs as well. The larger

I have an array of anchor tags returned by nokogiri that I need to coerce into a hash of values in order to output them as JSON. In that process I need to add some key/value pairs as well. The larger purpose of this is to create a JSON set that will be used to manually build a bookmarks file for Google Chrome. Chrome's bookmarks file looks like this:

    {开发者_如何转开发
   "checksum": "xxxxxxxxxxxxxxxxxxx",
   "roots": {
      "bookmark_bar": {
            "date_added": "12941058862382319",
            "id": "1101",
            "name": "One Site",
            "type": "url",
            "url": "http://www.onesite.com/"
         }, {
            "date_added": "12941058862383177",
            "id": "1102",
            "name": "Two Site",
            "type": "url",
            "url": "http://www.twosite.com"
         } ],
         "date_added": "11644473600000000",
         "date_modified": "12941058862390426",
         "id": "1",
         "name": "Bookmarks Bar",
         "type": "folder"
      }
    ... and so on

My anchor tags will supply the name and url, and then the date_added, id, and type values can be added.

I'm assuming I'll need to use Array.map somehow, but my skills with that are non-existent, and after reading a few other sites explaining it, I'm still nowhere closer to getting how to use it in my case.

All I could come up with is something like:

Hash[ bookmarks.map{ |bookmark| bookmark.content, bookmark.xpath("@href") }.to_json ]

but that complained about not being able to convert a string to an integer, so it obviously wasn't the right way to go about it.

Thanks for any help.


Ok, I think I've got it now. This should work

bookmarks.map{ |x| Hash["date_added" => "12941058862385244", "id" => bookmarks.index(x), "name" => x.content, "type" => "url", "url" => x.xpath("@href")] }

We'll see when Chrome goes to use it, but it looks good when I use JSON.pretty_generate to output.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号