lightswitch05 / table-to-json

Serializes HTML tables into JSON objects.
http://lightswitch05.github.io/table-to-json/
MIT License
756 stars 172 forks source link

Adding additional data #39

Closed siamkreative closed 7 years ago

siamkreative commented 7 years ago

Hey there!

This is a very handy jQuery plugin. I wonder how could I add additional data that is not a column of the table.

For instance, there I have a column with an image where I use extractor to get the image src. In addition to the image src, I would like to add the image width and height to the generated JSON. How would I do that?

Thanks

lightswitch05 commented 7 years ago

I'm glad you like the tool. I don't believe what you want can be accomplished within table-to-json, and it would be difficult to add the requested feature.

Your only option wI'll be to loop over the results, adding the new properties yourself. I hope that helps

siamkreative commented 7 years ago

Thanks for the fast answer! I guess I might write my own table to JSON as what I am doing is quite specific.

Mottie commented 7 years ago

Actually, it is possible using the extractor (demo)

var table = $('#example-table').tableToJSON({
  extractor: function(cellIndex, $cell) {
    var $img = $cell.find('img');
    return {
      name: $img.attr('alt'),
      width: $img.width(),
      height: $img.height()
    };
  }
});
siamkreative commented 7 years ago

Thanks a bunch @Mottie ! Does it work with multiple columns?

Here is my current implementation:

var table = $(el).tableToJSON({
    ignoreEmptyRows: true,
    headings: headings,
    textExtractor: {
        3: function (cellIndex, $cell) {
            // Get the image src attribute
            var imgUrl = $cell.find('a.image>img').attr('src');
            // Get bigger image URL
            if (imgUrl) {
                return imgUrl.replace('110px-', '640px-');
            }
        }
    }
});

The image that I want to get dimensions is in column 4. The other columns are text.

Mottie commented 7 years ago

Does it work with multiple columns?

Yes, you can see an example in the main readme.

siamkreative commented 7 years ago

Sorry I was not clear enough. I mean I can't get your example to work in my situation. I replaced the above code by:

var table = $(el).tableToJSON({
    ignoreEmptyRows: true,
    headings: headings,
    extractor: {
        3: function (cellIndex, $cell) {
            var $img = $cell.find('img');
            return {
                name: $img.attr('alt'),
                width: $img.width(),
                height: $img.height()
            };
        }
    }
});

In other words, how to get your example to work a specific column?

siamkreative commented 7 years ago

Finally got it working thanks for your precious help. Sorry for the trouble I caused 😋