I'm getting an input data in appscript in the form of binary data (docx file data) which looks something like below
I need this data to be converted into Base64 string. I tried using Utilities class to encode it into base64, however, it returns a few character string which is invalid. Is there any way to convert this form of data in appscript?
The current script is as below
function run() {
var inputData = Eventbus.get('encodedData');//this is received as binary data
var convertedData = Utilities.base64Encode(inputData);//need to encode to base64 but doesn't work
Eventbus.set('decodedData',convertedData);
}
Thanks
Saurabh
Related
I am building a web-app where I can upload a JSON file, update it, then download it. The output JSON is not valid because some characters changed through the process. I don't know where I'm wrong because even when I only do upload => download without updates the JSON is still not valid...
This is how I read the uploaded JSON:
readFile: function () {
var reader = new FileReader();
reader.onload = function(event) {
this.json = JSON.parse(event.target.result);
}.bind(this);
reader.readAsText(this.file);
}
Then I can edit (or not) the json object. Then I can download it with JSON.stringify(json).
When I try to read or validate the output JSON I get errors signaling invalid characters, for example:
Invalid characters in string. Control characters must be escaped for some lines in my editor.
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xac in position X: invalid start byte when I try to load it in python with open('output.json') as json_file: data = json.load(json_file)
Does using JSON.parse then JSON.stringify modifies the encoding or structure of the JSON? How can I avoid this effect?
UPDATE:
Original file can have some characters like \u2013, \u2014, \u201d, \u00e7 but those characters are transformed into things like this � or invisible characters in the output JSON, which I guess make it not valid.
Try to add 'UTF-8' as a second parameter to the readAsText function as follows :
reader.readAsText(this.file,'UTF-8');
Here I want to convert my encoded url into JSON format. The encoded url is:
http://localhost:63342/AngularJs/services/e_cell.html#!/%7B%22book%22:%22ABC%22%7D
As much as I understand from your URL you are trying to post this %7B%22book%22:%22ABC%22%7D data in query string.
So first you need to decode your URL encoded data into an string which can be parsed. For that you can take help of decodeURIComponent() javascript API.
decodeURIComponent() - this function decodes an encoded URI component back to the plain text i.e. like in your encoded text it will convert %7B into opening brace {. So once we apply this API you get -
//output : Object { book: "ABC" }
This is a valid JSON string now you can simply parse. So what all you need to do is -
var formData = "%7B%22book%22:%22ABC%22%7D";
var decodedData = decodeURIComponent(formData);
var jsonObject = JSON.parse(decodedData);
console.log(jsonObject );
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string
The decodeURIComponent function will convert URL encoded characters back to plain text.
var myJSON = decodeURIComponent("%7B%22book%22:%22ABC%22%7D");
var myObject = JSON.parse(myJSON);
What I need to do is best descriped as example.
Previously, I had the following code:
content = u'<?xml version="1.0" encoding="windows-1251"?>\n' + ... #
with open(file_name, 'w') as f:
f.write(content.encode('cp1251'))
f.close;
Now I want to modify the architecture of my entire app and send the string which is supposed to be the file content to client via JSON and to generate the file via javascript.
So, now my code looks something like this:
response_data = {}
response_data['file_content'] = content.encode('cp1251')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)}) # error generated
The problem is that I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 53: ordinal not in range(128)
I also tried the second option this way:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False).encode('utf8')}) # error generated
Then, on client, I try to covert utf8 to windows-1251.
$.post ('/my_url/', data, function(response) {
var file_content = JSON.parse(response.content).file_content;
file_content = UnicodeToWin1251(file_content);
...but...I get distorted symbols.
I know I am doing something terribly wrong here and am likely to mess up things with encoding, but still it's been an entire day I couldn't solve this issue. Could someone give a hint where my mistake is ?
Both XML and JSON contain data that is Unicode text. The XML declaration merely tells your XML parser how to decode the XML serialisation of that data. You wrote the serialisation by hand so to match the XML header, you had to encode to CP-1251.
The JSON standard states that all JSON should be encoded in either UTF-8, UTF-16 or UTF-32, with UTF-8 the standard; again, this is just the encoding for the serialisation.
Leave your data as Unicode, then encode that data to JSON with the json library; the library takes care of ensuring you get UTF-8 data (in Python 2), or gives you Unicode text (Python 3) that can be encoded to UTF-8 later. Your Javascript code will then decode the JSON again at which point you have Unicode text again:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
There is no need whatsoever to send binary data over JSON here, you are sending text. If you Javascript code then generates the file, it is responsible for encoding to CP-1251, not your Python code.
If you must put binary data in a JSON payload, you'll need to encode that payload to some form of text. Binary data (and CP-1251-encoded text is binary data) could be encoded in text as Base-64:
import base64
response_data = {}
response_data['file_content'] = base64.encodestring(content.encode('cp1251')).decode('ascii')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
Base64 data is encoded to a bytestring containing only ASCII data, so decode it as ASCII for the JSON library, which expects text to be Unicode text.
Now you are sending binary data, wrapped in a Base64 text encoding, to the Javascript client, which now has to decode the Base64 if you need the binary payload there.
I have a encoded JSON string returning the following sting which I am displaying on my webpage from a database call.
{"Value 1":"1234","Value 2":"123456"}
How do I decode this string and also format the data to be displayed in a table?
I am at a lost as how to do this. Thanks
Here is how to turn a string containing a JSON into an object:
JSON.parse('{"Value 1":"1234","Value 2":"123456"}');
Does anyone know of any simple javascript that I can use to turn a base64 string into an image (jpg format preferably), so that I can save the image to a file? This is for a signature pad application. I can get the signature into a base64 format, but need to save the signature as an image file to use for embedding into a Crystal Report.
I have tried this method in a JSP page to print the image from a base64 string, I guess this should hold good for javascript too. Do not have sample data for now to verify, but here's how I would try it.
var oImg=document.createElement("img");
var baseString = null; //the base64 string you have
var imsc = 'data:image/jpg;base64, '+baseString;
oImg.setAttribute('src', imsc);
document.body.appendChild(oImg);