jszip icon indicating copy to clipboard operation
jszip copied to clipboard

Is it possible to zip a javascript object?

Open whosyourtaco opened this issue 6 years ago • 5 comments

I'm trying to create a zip file that contains several .json files. The json files' data is provided by the client and are standard javascript objects in format.

I get an error that the data can't be read since they aren't in a JS supported format, like Blob.

The only way I've managed to get past this is by calling JSON.stringify() on the data before it's zipped, but that of course results in zipped json files that contain the stringified object, which defeats the purpose of the json file.

Is that possible? Am I missing something in the configuration?

Thanks!

whosyourtaco avatar Apr 11 '19 11:04 whosyourtaco

Is that possible?

Nope

jimmywarting avatar Jul 04 '19 09:07 jimmywarting

Use JSON.parse() to convert JSON to a JavaScript object when you need to read it as a JavaScript object.

YukariTea avatar Jan 06 '20 04:01 YukariTea

Is this still not possible is there any way you can change the type to -> type : "json". making and ziping a json object or json string

mguti3 avatar Jun 29 '23 19:06 mguti3

I don't think jszip should support this... sry

Any archiving library should not have to deal with having to support converting any arbitrary cbor / json / protobuf or anything else to / from json or anything else like it. the purpose of a zip library is to work with only files (binary data)

if you want to store a javascript object as json then stringify it yourself using JSON.stringify(). and append a string / typed array / blob

if zip should do anything then it should try it's best to convert whatever it receives into binary following the same WebIDL rules Blob constructor works with. meaning: if it's a blob, arraybuffer or arraybuffer view, then perfect it knows how to convert that data into binary... if not then it should fallback into using: String(unknown) or better yet just do: new TextEncoder().encode(unkown) which is the equivalent but returns a better binary format to work with.

following this convention then you could take advantage of Symbol.toPrimitive and do something like this:

const object1 = {
  foo: 123,
  [Symbol.toPrimitive](hint) {
    if (hint === 'string') {
      return JSON.stringify(object1);
    }
    return null;
  }
}

new TextDecoder().decode(
  new TextEncoder().encode(object1)
) // '{"foo":123}'

console.log(`${object1}`) // '{"foo":123}'

jimmywarting avatar Jun 29 '23 22:06 jimmywarting