Golang backend to javascript JSON Parse - javascript

I am using the gorilla websocket library for golang: http://www.gorillatoolkit.org/pkg/websocket
This is the code I am using to create the websocket connection:
conn, err := upgrader.Upgrade(w, r, nil)
Having an issue with sending JSON from golang to javascript. I can get it working but have to do what seem to be unnecessary steps. Here is the basics of the golang backend that does not work:
type clientDB struct{
ChunksWritten int64
ChunksRead int64
BytesWritten int64
BytesRead int64
DataBytesWritten int64
DataBytesRead int64
ActivePeers int
TotalPeers int
TorrentHashString string
}
fullClientDB := new(clientDB) //creating a new clientDB struct
b, err := json.Marshal(fullClientDB)
if err != nil {
fmt.Println(err)
return
}
conn.WriteJSON(b)
When I use JSON.parse in javascript I get the following response:
var clientUpdate = JSON.parse(evt.data);
eyJDaHVua3NXcml0dGVuIjowLCJDaHVua3NSZWFkIjowLCJCeXRlc1dyaXR0ZW4iOjU0NDgxLCJCeXRlc1JlYWQiOjc4NzgyLCJEYXRhQnl0ZXNXcml0dGVuIjowLCJEYXRhQnl0ZXNSZWFkIjowLCJBY3RpdmVQZWVycyI6MCwiVG90YWxQZWVycyI6NDMsIlRvcnJlbnRIYXNoU3RyaW5nIjoiOWY5MTY1ZDlhMjgxYTliOGU3ODJjZDUxNzZiYmNjODI1NmZkMTg3MSJ9
I can get it working making the following changes:
conn.WriteJSON(string(b))
Then in javascript I actually parse the data TWICE.
var clientUpdate = JSON.parse(evt.data);
var clientUpdateJSON = JSON.parse(clientUpdate);
After that I can access the data correctly as a JSON object. Is there something I'm missing about sending JSON objects from golang to javascript over websockets?

The gorilla websocket package automatically encodes to JSON so using the standard library to encode as well was just encoding it twice, causing it to show up as base64.
Thanks guys!

Related

TypeError: expected bytes-like object, not str

I know this question has been asked much times, but please look once in my problem.
I am sending base64 image data from angular to python flask but when I am processing that base64 data on flask server(python3) then it is giving me the error
TypeError: expected bytes-like object, not str
My Javascript code is:
window['__CANVAS'].toDataURL("image/png");
Output of the above line is:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUg....."
I am receiving same data on flask server as string.
Code on python server that is using above base 64 data is:
def convert_to_image(base64_code):
image_64_decode = base64.decodebytes(base64_code)
image_result = open('baseimage.jpg', 'wb')
image_result.write(image_64_decode)
img_rgb = cv2.imread('baseimage.jpg')
return img_rgb
then it is giving the following error trace:
File "/home/shubham/py-projects/DX/Web/app/base64toimage.py", line 10, in convert_to_image
image_64_decode = base64.decodebytes(base64_code)
File "/usr/lib/python3.5/base64.py", line 552, in decodebytes
_input_type_check(s)
File "/usr/lib/python3.5/base64.py", line 521, in _input_type_check
raise TypeError(msg) from err
TypeError: expected bytes-like object, not str
above python function working fine if I am converting the image using this function
import base64
with open("t.png", "rb") as imageFile:
str = base64.b64encode(imageFile.read())
print str
please help me to solve this question? I am new to python.
base64.decodebytes only accepts byte arrays, use base64.b64decode instead it accepts Strings as well
Encoded bytes will do.
bytes(base64_code, encoding='utf-8')

How to create ajersey restful method that can accept three arrays of strings

I have been trying to send string arrays to a restful services without any luck. I have written this
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getBackgroundImages(#QueryParam("missions") String[] missions,
#QueryParam("objects")String[] objects,
#QueryParam("dates")String[] dates) {
........
return generateTxt();
}
on the javascript side I have this
var missions = new Array("One", "Two");
var objects = new Array("objOne" ,"objTwo");
var dates = new Array("1967-11-07","1977-12-17");
$.ajax({
url: "myurl/rest/UploadBackgroundFile/",
data: {'missions':missions,'objects':objects,'dates':dates},
success: function (data) {
arr = JSON.parse(data);
$('.container-fluid').css('background-image','url('+arr[0].img+')');
}
});
my problem is that this is not working and I am getting this exception
org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type
public java.lang.String UploadBackgroundFile.getBackgroundImages(java.lang.String[],java.lang.String[],java.lang.String[])
if I change the parameters to normal string and send strings from the javascript side than the method will work.
so the question is how to send and receive string arrays from the jquery ajax to the jersey restful method.
with regards,
es
Server side, you have to change the string array to a List<String> to make it work.
Client side, you can see this to help you how to send the datas. I know in title it's write PHP, but it's well explained.

How can I send javascript as a string in a JSON parameter

I am building dynamic javascript in C# and sending it back to a single page application in a JSON request.
The problem is, the javascript/jquery in the JSON parameter breaks the JSON. How do I properly escape this?
Here is the code... it will combine many small segments of js from files into a string and inject it into a page.
Many thanks!
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader("dynamic.js"))
{
// Read the stream to a string, and write the string to the console.
dynamicJS = sr.ReadToEnd();
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
// user has been authenticated return data and JS to the front end
return $"{{ \"Email\": \"{userDetails.Email}\", \"DisplayName\": \"{userDetails.DisplayName}\", \"Services\": {safeServices.SerializeToJsonString()}, \"PageElements\": \"{pageURLs}\", \"DyanamicJS\": \"{dynamicJS}\" }}";

recieving broken JSON data in javascript

I have PageMethod in javascript which is receiving JSON data from C#.
In C# its getting full xml data from database and converting into JSON and sending back to PageMethod.
JSON Converted data is about 33kb, but i'm not able to receive full data in javascript. I'm receiving only 9 kb of data. any solution for getting full data in java script.
PageMethod.methodName(onSuccess,OnFail);
function OnSuccess(result)
{
alert(result);
}
function OnFail()
{
alert("Error");
}
C# code as follows,
ParamResult objParamResult = new ParamResult();
objParamResult.ResultDt = string.Empty;
DataTable XmlMainSub = objCBTag.getParamPickupDetailsDB();
string myData = XmlMainSub.Rows[0][0].ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(myData);
string jsonText = JsonConvert.SerializeXmlNode(doc);
return jsonText;
instead of
string jsonText = JsonConvert.SerializeXmlNode(doc);
you can use
string jsonText = new JavaScriptSerializer().Serialize(doc).toString();
you need to use namespace for this
using System.Web.Script.Serialization;
After i made lot of research, i found that its not possible to send JSON data from C# to javascript which is more than 8KB or 9KB in size.
And i solved this problem by making use of c# generics which is Dictionary which contains Key and Value Pair. I Tried to loop XML Data which is coming from database and stored in a dictionary object.
Then i passed it to javascript. There i able to receive full data without any error.

How to convert a string to an inputstream in Bioclipse javascript editor?

I'm trying to save an a string to a file in with a javascript in the Bioclipse workbench, by using
ui.save( "filename", "my string" );
...but get an error that ui.save takes only an inputstream as the second parameter.
How can I convert a string to an inputstream in the Bioclipse javascript context?
(Btw, I think Bioclipse uses the Rhino Javascript implementation)
In this situation we have to fall back to Java.
You are trying to call the method ui.save which according to man ui.save looks like this:
> man ui.save
---------------------------------------------
ui.save(String filePath, InputStream content)
---------------------------------------------
Save the content of the InputStream to the given path.
So this method wants an InputStream. Rhino allows us to instantiate Java objects. This can probably be made much nicer...
var stream = new java.io.ByteArrayInputStream(
new java.lang.String("Example String").getBytes("UTF-8") );
And then we call the method with this stream, (and an existing path where to save the file)
ui.save("/test/test.txt", stream);
Here's a page describing java interop using Rhino: http://www.mozilla.org/rhino/ScriptingJava.html

Categories

Resources