Stuk / jszip

Create, read and edit .zip files with Javascript
https://stuk.github.io/jszip/
Other
9.75k stars 1.3k forks source link

Is it possible to zip a javascript object? #595

Open whosyourtaco opened 5 years ago

whosyourtaco commented 5 years ago

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!

jimmywarting commented 5 years ago

Is that possible?

Nope

YukariTea commented 4 years ago

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

mguti3 commented 1 year ago

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

jimmywarting commented 1 year ago

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}'
AcidRaZor commented 2 weeks ago

@jimmywarting If that's the case, why can I add json files to a ZIP archive on windows and not get this error or have to worry about JSON.stringify?