0

I am building a small JS app with user configurable settings. The settings are stored in a JSON file. On load the app loads the settings files (jQuery.getJSON(....)) then performs their work which may include changes to the current settings and then save the settings back to the the sharepoint site.

However when saving the settings back to the SP site the file is being encoded in UCS2LE instead of UTF-8. Then the next time the app is loaded getJSON fails to parse the file properly.

My code is as follows:

function str2buf(str){
  let buf=new ArrayBuffer(str.length*2);
  let bufView = new Uint16Array(buf);
  for(let i=0; strLen=str.length;i<strLen;i++){
    bufView[i]=str.charCodeAt(i);
  }
}
...
let d=str2buf(JSON.stringify(settings));
$.ajax({
  url: <site url>,
  type:'Post',
  data:d,
  dataType:'json',
  processData:false,
  headers:{
    'accept':'applictation/json';odata=verbose',
    'X-requestDigest':<REQUEST_DIGEST_VALUE>
  }
}).done(...).fail(...);

I've tried explicitly setting contentType option with 'application/x-www-form-urlencoded; charset=UTF-8' and other variants to no avail.

How can I ensure that the file is uploaded/stored as UTF-8?

EDIT:

After logging the attempt to parse the JSON file I originally saved I notice that the file comes back with a space after every character.

{ f i l e N a m e : " m y S e t t i n g s . t x t " .... }
  • To upload your file, I guess you use /_api/web/GetFolderByServerRelativeUrl('folder')/files/add(url='filename',overwrite=true)? But I think the problem is due to the str2buf function. Did you try with different browsers? Did you try with using another encoding function (e.g. developers.google.com/web/updates/2014/08/…) ? – AymKdn Aug 1 '17 at 7:32
  • Yes. that is the SP api I am calling. Based on this example. dev.office.com/sharepoint/docs/sp-add-ins/… Adding the text string directly to the 'data' key seemed to work well enough. Bypassing the str2buf function all together. – Wanderer Aug 1 '17 at 17:04
0

Bypassing the str2buf worked.

let d=JSON.stringify(settings);
$.ajax({
  url: <site url>,
  type:'Post',
  data:d,
  dataType:'json',
  processData:false,
  headers:{
    'accept':'applictation/json';odata=verbose',
    'X-requestDigest':<REQUEST_DIGEST_VALUE>
  }
}).done(...).fail(...);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.