Search code examples
jsonsvgbase64jq

Store an SVG image in JSON or not?


I do not know if I'm asking in the correct "Stack", but at the moment I seem to be the most appropriate one. Let me also note if I'm wrong, I'll immediately move the question to another Stack.

I need to save a vector image (most likely it will be SVG format). We are considering how to memorize this image. The point is that we prefer to use only a JSON file, which means that you have to convert the SVG image to at least Base64, but is it lossless or not?

The alternative would be to save the local path of this SVG image in a field in the JSON file. This image and JSON files should not be sent over the network and conversion from Bas64 to SVG should not be too slow considering a PC environment. Based on your experiences, what do you recommend doing?


Solution

  • You could use jq to encode the contents of the .svg file as a JSON string, e.g.

    jq -Rs . media.svg
    

    Of course, you would probably want to use a more complex jq filter to embed the contents of the .svg file in your JSON.

    As implied by the answers at Does SVG support embedding of bitmap images? you should not need to base64-encode a SVG, but if you do need to base64-encode something, you can use jq's @base64 filter. You can verify this works for some file (say FILENAME) by decoding the string and comparing with the original. If your jq has @based64d, this can be done by:

    diff FILENAME <(jq -Rs @base64 FILENAME | jq -r @base64d)