How to parse unicode character to xml format standard - javascript

I have some problem such as. When I call webservice and Webservice return Dataset and output as following:
"\u003cNewDataSet\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e81\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e81\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Airside sdda\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e82\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e82\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Landsite\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e85\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e85\u003c/Column1\u003e\r\n \u003cszDescription\u003eAKL Arrival\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e0\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n \u003cTable\u003e\r\n \u003clSellLocID\u003e886\u003c/lSellLocID\u003e\r\n \u003cColumn1\u003e886\u003c/Column1\u003e\r\n \u003cszDescription\u003e886-PreOrder\u003c/szDescription\u003e\r\n \u003cbPreOrder\u003e-1\u003c/bPreOrder\u003e\r\n \u003c/Table\u003e\r\n\u003c/NewDataSet\u003e"
I want it output XML format.

If this is the actual character data you have got, then you need to do some string replacements. Assuming the string is the value of a variable s, then you can do this:
s = s.replace(/\\u003c/gi,"<").replace(/\\u003e/gi,">").replace(/\\r\\n/g, "\n");

Related

In the javascript unable to convert string to variable

One of my requirement in the javascript, I am trying to convert the string which is passing from the database to javascript object.
Step1:
String passing from the databse:
"validator":["required","numeric","maxLength:14","{type: amountValidate}"]
Step2: Converting to javascript object using JSON.Parse() method, output as follows:
validator: Array(4)
0: "required"
1: "numeric"
2: "maxLength:14"
3: "{type: amountValidate}"
length: 4
Expected output is:
In the below code amountValidate is converting into the function by tabulator js api.
validator:["required","numeric","maxLength:14",{
type:amountValidate,
}]
Since I am applying the below function to the type:amountValidate, it should behave as a variable and it should not be in the double quotes.
var amountValidate = function(cell, value, parameters){
var regex = /^\s*-?(\d+(\.\d{1,2})?|\.\d{1,2})\s*$/
var n = value.match(regex);
if(n !== null){
return true;
}else{
return false;
}
}
Thanks in advance.
The main problem here is that your string is not a valid JSON. Should be something like:
'{"validator": ["required","numeric","maxLength:14", {"type": "amountValidate"}]}'
There are multiple json formatters/validators online, like this one, that you could use to check it.

Javascript- convert content in textbox to key value pair

I have a textbox which accepts user defined key value pairs like:
{'Apple':'Red', 'Lemon':'Green'} and i want it to be converted to an array of key value pair.
I have code:
var color= document.getElementById('txtColor').value;
The problem is i get it just as a string if i try: color['Apple'] it shows undefined; whereas i expect 'Red'. How can i do the conversion so that i get something like:
var color={'Apple':'Red', 'Lemon':'Green'}
and get value 'Red' on color['Apple'].
Thanks in advance.
I have a similar usecase. You have to JSON.parse() the value.
var obj = JSON.parse(document.getElementById('txtColor').value.replace(/'/g, '"'));
console.log(obj['Apple']);
<textarea id="txtColor">{'Apple':'Red', 'Lemon':'Green'}</textarea>
I assume following
let color = document.getElementById('txtColor').value; // This line returns {'Apple':'Red', 'Lemon':'Green'}
If I'm correct you can do following
try {
// Here you can write logic for format json ex. Convert single quotes to double quotes
// This may help to convert well formatted json string https://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript
let colorJson = JSON.parse(color);
console.log(colorJson["Apple"]) // This will return your expected value.
} catch(e) {
console.log('Invalid json format')
}
var color = document.getElementById('txtColor').value;
//JSON.stringify will validate the JSON string
var jsonValidString = JSON.stringify(eval("(" + color + ")"));
//If JSON string is valid then we can conver string to JSON object
var JSONObj = JSON.parse(jsonValidString);
//We can use JSON.KeyName or JSON["KeyName"] both way you can get value
console.log(JSONObj.Apple, " --- ", JSONObj["Apple"]);
console.log(JSONObj.Lemon, " --- ", JSONObj["Lemon"]);
<input id="txtColor" value="{'Apple':'Red', 'Lemon':'Green'}" type="text" />

How to format Base64 encoded string while sending in JSON

I want to format base64 encoded string, when I send the below string in JSON request - I am getting JSON validation error because this string is not formatted properly. I couldn't find any good utility which converts from base64 encoded string to the proper one.
Is there any utility in Java/Groovy or Javascript to format in a single line.
Appreciated your help
{
"data": "JVBERi0xLjMNJeLjz9MNCjcgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgNzk0NS9PIDkvRSAzNTI0
L04gMS9UIDc2NTYvSCBbIDQ1MSAxMzddPj4NZW5kb2JqDSAgICAgICAgICAgICAgICAgICAgICAg
DQoxMyAwIG9iag08PC9EZWNvZGVQYXJtczw8L0NvbHVtbnMgNC9QcmVkaWN0b3IgMTI+Pi9GaWx0
ZXIvRmxhdGVEZWNvZGUvSURbPDREQzkxQTE4NzVBNkQ3MDdBRUMyMDNCQjAyMUM5M0EwPjxGNkM5
MkIzNjhBOEExMzQwODQ1N0ExRDM5NUEzN0VCOT5dL0luZGV4WzcgMjFdL0luZm8gNiAwIFIvTGVu
Z3RoIDUyL1ByZXYgNzY1Ny9Sb290IDggMCBSL1NpemUgMjgvVHlwZS9YUmVmL1dbMSAyIDFdPj5z
dHJlYW0NCmjeYmJkEGBgYmCyARIMIIKxAUgwpwIJNkcg8eUYAxMjwzSQLAMjucR/xp1fAAIMAEyk
BvANCmVuZHN0cmVhbQ1lbmRvYmoNc3RhcnR4cmVmDQowDQolJUVPRg0KICAgICAgICANCjI3IDAg
b2JqDTw8L0ZpbHRlci9GbGF0ZURlY29kZS9JIDY5L0xlbmd0aCA1OC9TIDM4Pj5zdHJlYW0NCmje
YmBgYGFgYPzPAATcNgyogJEBJMvRgCzGAsUMDA0M3Azc0x50JoA4zAwMWgIQLYwsAAEGAL/iBRkN
CmVuZHN0cmVhbQ1lbmRvYmoNOCAwIG9iag08PC9NZXRhZGF0YSAxIDAgUi9QYWdlcyA1IDAgUi9U
eXBlL0NhdGFsb2c+Pg1lbmRvYmoNOSAwIG9i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U6MjQ6MTMtMDQ6MDA8
L3htcDpNZXRhZGF0YURhdGU+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICAgICA8cmRmOkRl
c2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpwZGY9Imh0dHA6Ly9ucy5h
ZG9iZS5jb20vcGRmLzEuMy8iPgogICAgICAgICA8cGRmOlByb2R1Y2VyPkFjcm9iYXQgRGlzdGls
bGVyIDQuMCBmb3IgV2luZG93czwvcGRmOlByb2R1Y2VyPgogICAgICA8L3JkZjpEZXNjcmlwdGlv
bj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6
eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iPgogICAgICAgICA8eG1wTU06
RG9jdW1lbnRJRD51dWlkOjA4MDVlMjIxLTgwYTgtNDU5ZS1hNTIyLTYzNWVkNWMxZTJlNjwveG1w
TU06RG9jdW1lbnRJRD4KICAgICAgICAgPHhtcE1NOkluc3RhbmNlSUQ+dXVpZDo2MmQ2YWU2ZC00
M2M0LTQ3MmQtOWIyOC03YzRhZGQ4ZjllNDY8L3htcE1NOkluc3RhbmNlSUQ+CiAgICAgIDwvcmRm
OkRlc2NyaXB0aW9uPgogICA8L3JkZjpSREY+CjwveDp4bXBtZXRhPgogICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
IAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAog
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAKICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgCiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg
ICAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgCjw/eHBhY2tldCBlbmQ9InciPz4N
CmVuZHN0cmVhbQ1lbmRvYmoNMiAwIG9iag08PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgNC9M
ZW5ndGggNDgvTiAxL1R5cGUvT2JqU3RtPj5zdHJlYW0NCmjeMlUwULCx0XfOL80rUTDU985MKY62
BIoFxeqHVBak6gckpqcW29kBBBgA1ncLgA0KZW5kc3RyZWFtDWVuZG9iag0zIDAgb2JqDTw8L0Zp
bHRlci9GbGF0ZURlY29kZS9GaXJzdCA0L0xlbmd0aCAxNjcvTiAxL1R5cGUvT2JqU3RtPj5zdHJl
YW0NCmjePMvBCsIwEEXRX5mdDaKdxCpVSqFY3AkuBNexSelA6EAyRfx7A4qPu3znAAhNU3aLTByL
wVkKb1Weo7dCPPdWfNGfDOYdzFGj0VivtV4hrn6vrK40RE48Cjw4Oqi3qMoruz/WuwxrvTeV3m2w
+uJbZLcMPhZdxk8r0FMSCsFHqLYII0d40Oz4lVR5Jwm+uE+UIGdBfBK49RcYKXjVth8BBgBnZztk
DQplbmRzdHJlYW0NZW5kb2JqDTQgMCBvYmoNPDwvRGVjb2RlUGFybXM8PC9Db2x1bW5zIDMvUHJl
ZGljdG9yIDEyPj4vRmlsdGVyL0ZsYXRlRGVjb2RlL0lEWzw0REM5MUExODc1QTZENzA3QUVDMjAz
QkIwMjFDOTNBMD48RjZDOTJCMzY4QThBMTM0MDg0NTdBMUQzOTVBMzdFQjk+XS9JbmZvIDYgMCBS
L0xlbmd0aCAzNy9Sb290IDggMCBSL1NpemUgNy9UeXBlL1hSZWYvV1sxIDIgMF0+PnN0cmVhbQ0K
aN5iYmBgYGLkPcLEwD+ViYGhh4mBkYWJ8bEkkM0IEGAAKlkDFA0KZW5kc3RyZWFtDWVuZG9iag1z
dGFydHhyZWYNCjExNg0KJSVFT0YNCg==
"
}
// if this is your Base64 encoded string
var str = 'VGhpcyBpcyBhbiBhd2Vzb21lIHNjcmlwdA==';
// make URL friendly:
str = str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
// reverse to original encoding
str = (str + '===').slice(0, str.length + (str.length % 4));
str = str.replace(/-/g, '+').replace(/_/g, '/');
If By Formatting what you mean is making it URL friendly, Above Goes the Code!
If you are referring to encoding and decoding of the String,
You can use btoa() and atob() to convert to and from base64 encoding
If I understood well you have problems to make a valid JSON with an base64 string.
I would recommend this:
Use the JavaScript function
JSON.stringify(encodedData) which returns an escaped string that you can use it with no problems in your JSON afterwards.
The encoded data is a PDF file, so it is binary data and you should not attempt to convert it to a String.
Instead, deal with the Bytes, for instance, by writing it to a file. In Groovy:
// String s = <your JSON>
Byte[] b = new groovy.json.JsonSlurper().parseText(s) // no errors here, the JSON you supplied is valid
."data" // GPath syntax for getting the "data" element in the JSON
.replaceAll (/\s/, "") // remove spaces and newlines
.decodeBase64() // returns an array of Byte
new File("somefile.pdf").bytes = b
Opening somefile.pdf, I can see:
Adobe Acrobat PDF Files
Adobe Portable Document Format (PDF) is a universal file format that preserves allof the fonts, formatting, colours and graphics of any source document, regardless ofthe application and platform used to create it.
...
If the encoded data had in fact been a String, you could get the original String just by String x = new String(b).

Converting string containing array of arrays into JSON object

I have an API that returns me a string that contains an array of arrays. The arrays contains strings, like here:
"[['cat','mouse'],['duck','fish'],['lion','zebra']]"
and I want to convert it into a JSON object.
I've tried JSON.parse, but it's giving me an error
Blockquote
[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:0
^
SyntaxError: Unexpected token '
The string that im trying to turn into an object is this one:
"[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kaliningrad)','+03:00 (Europe/Kaliningrad)'],['-01:00 (Etc/GMT+1)','-01:00 (Etc/GMT+1)'],['AKST (America/Anchorage)','AKST (America/Anchorage)'],['ART (America/Argentina/Buenos_Aires)','ART (America/Argentina/Buenos_Aires)'],['AST (America/Puerto_Rico)','AST (America/Puerto_Rico)'],['AST (Asia/Baghdad)','AST (Asia/Baghdad)'],['AST (Atlantic/Bermuda)','AST (Atlantic/Bermuda)'],['BRT (America/Sao_Paulo)','BRT (America/Sao_Paulo)'],['CET (CET)','CET (CET)'],['CET (Europe/Amsterdam)','CET (Europe/Amsterdam)'],['CET (Europe/Brussels)','CET (Europe/Brussels)'],['CET (Europe/Budapest)','CET (Europe/Budapest)'],['CET (Europe/Madrid)','CET (Europe/Madrid)'],['CET (Europe/Oslo)','CET (Europe/Oslo)'],['CET (Europe/Paris)','CET (Europe/Paris)'],['CET (Europe/Prague)','CET (Europe/Prague)'],['CET (Europe/Vienna)','CET (Europe/Vienna)'],['CET (Europe/Warsaw)','CET (Europe/Warsaw)'],['CET (Europe/Zurich)','CET (Europe/Zurich)'],['CLST (America/Santiago)','CLST (America/Santiago)'],['COT (America/Bogota)','COT (America/Bogota)'],['CST (America/Chicago)','CST (America/Chicago)'],['CST (America/Costa_Rica)','CST (America/Costa_Rica)'],['CST (America/Mexico_City)','CST (America/Mexico_City)'],['CST (Asia/Shanghai)','CST (Asia/Shanghai)'],['CST (Asia/Taipei)','CST (Asia/Taipei)'],['CST (Australia/Adelaide)','CST (Australia/Adelaide)'],['EAT (Africa/Nairobi)','EAT (Africa/Nairobi)'],['EET (EET)','EET (EET)'],['EET (Europe/Istanbul)','EET (Europe/Istanbul)'],['EET (Europe/Kiev)','EET (Europe/Kiev)'],['EST (America/Indiana/Indianapolis)','EST (America/Indiana/Indianapolis)'],['EST (America/New_York)','EST (America/New_York)'],['EST (Australia/Brisbane)','EST (Australia/Brisbane)'],['EST (Australia/Melbourne)','EST (Australia/Melbourne)'],['EST (Australia/Sydney)','EST (Australia/Sydney)'],['GMT (Europe/Dublin)','GMT (Europe/Dublin)'],['GMT (Europe/London)','GMT (Europe/London)'],['GST (Asia/Dubai)','GST (Asia/Dubai)'],['HKT (Asia/Hong_Kong)','HKT (Asia/Hong_Kong)'],['HST (Pacific/Honolulu)','HST (Pacific/Honolulu)'],['ICT (Asia/Bangkok)','ICT (Asia/Bangkok)'],['IST (Asia/Jerusalem)','IST (Asia/Jerusalem)'],['IST (Asia/Kolkata)','IST (Asia/Kolkata)'],['JST (Asia/Tokyo)','JST (Asia/Tokyo)'],['KST (Asia/Seoul)','KST (Asia/Seoul)'],['MSK (Europe/Moscow)','MSK (Europe/Moscow)'],['MST (America/Denver)','MST (America/Denver)'],['MST (America/Phoenix)','MST (America/Phoenix)'],['MST (MST)','MST (MST)'],['MYT (Asia/Kuala_Lumpur)','MYT (Asia/Kuala_Lumpur)'],['NZDT (Pacific/Auckland)','NZDT (Pacific/Auckland)'],['PET (America/Lima)','PET (America/Lima)'],['PHT (Asia/Manila)','PHT (Asia/Manila)'],['PST (America/Los_Angeles)','PST (America/Los_Angeles)'],['PYST (America/Asuncion)','PYST (America/Asuncion)'],['SAST (Africa/Johannesburg)','SAST (Africa/Johannesburg)'],['SGT (Asia/Singapore)','SGT (Asia/Singapore)'],['TJT (Asia/Dushanbe)','TJT (Asia/Dushanbe)'],['UTC (UTC)','UTC (UTC)'],['VET (America/Caracas)','VET (America/Caracas)'],['WET (Europe/Lisbon)','WET (Europe/Lisbon)'],['WST (Australia/Perth)','WST (Australia/Perth)']]"
This is not valid JSON. You have to replace the ' characters with ".
Your JSON is invalid as mentioned in the first answer but this is a quick fix.
Say you have:
a = "[['+00:00 (Etc/GMT)','+00:00 (Etc/GMT)'],['+03:00 (Europe/Kalini..
Then replace the ' with ":
a = a.replace(/'/g, '"');
Then parse it to JSON:
a = jQuery.parseJSON(a)
Then you have a valid JSON, try console.table(a) to see your valid json!

JSON Serialization error with simplejson

I have the following code:
data = {'services': [u'iTunes'],
'orders': [u'TestOrder', u'Test_April_Titles_iTunes'],
'providers': ''}
return HttpResponse(simplejson.dumps(data))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py" in default
178. raise TypeError(repr(o) + " is not JSON serializable")
Exception Type: TypeError at /reports/change_dropdown/
Exception Value: [u'iTunes'] is not JSON serializable
What do I need to do to serialize this dictionary with a list inside it?
The problem is that itunes is a non-JSON compatible type.
To solve provide default type to convert non-JSON compatible types when serializing:
simplejson.dumps(data, default=str))
or even:
def handler(val):
if isinstance(val, unicode)
return str(val)
else:
return val
simplejson.dumps(data, default=handler))
The advantage of the second option is you can handle sets (e.g., convert to list), dates (e.g., convert to int timetstamp), etc.
Converting from unicode to str worked here:
data['services'] = [str(item) for item in data['services']]
data['orders'] = [str(item) for item in data['orders']]
data['providers'] = [str(item) for item in data['providers']]

Categories

Resources