Passing an array from javascript to ruby with sinatra - javascript

What I want to accomplish is to pass a 2D array from javascript to something that ruby will recognize. All objects are strings
I have been using gon-sinatra, but it doesn't do exactly what I need.
I can pass store the string I want to pass as gon.text doing
#temp = gon.text
array.push(#temp)
This doesn't work because it shows gon.text as a nil object type, when I want it as a string. gon.text.to_s returns an empty string, so when I try to display it, nothing happens. alert("<%= #temp %>") // displays an empty string
I'm at a bit of a loss here and don't know the best way to approach this. Would it be better to store the array as a json, and then read in the json using ruby instead?

Yes. Convert your array to json(a string) with js:
var data = JSON.stringify(yourArray);
Send the string to your ruby script. Then parse the string into an Array with ruby:
require 'json'
arr = JSON.parse(the_string)

In Javascript you do something like the following:
var myArray = [ ['str1','str2'], ['str3','str4'] ];
$.get('/endpoint', { myArray: myArray })
And your endpoint with sinatra would be:
get 'endpoint' do
myArrayStr = params[:myArray]
error!('invalid array') unless myArrayStr
#myArray = JSON.parse(myArrayStr)
gon.rabl 'goners/yourFile.rabl', :instance => self
end
And in your gon file you would reference this with:
alert(gon.myArray[0][0]); // str1

Related

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)

How to convert a string to JSON format?

I was getting list in array form. So at first place i converted array list to string-
var myJsonString = JSON.stringify(result);
myJsonString="[{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},
{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}]"
But again i need to convert myJsonString to Json format, What i need to do? I mean i need to replace 1st" and last ", I guess
You need to call parse now.
JSON.parse(myJsonString)
First, if you ever find yourself building a JSON string by concatenating strings, know that this is probably the wrong approach.
I don't really understand how the first line of your code relates to the second, in that you are not doing anything with JSON-encoded string output from result, but instead just overwriting this on the following line.
So, I am going to limit my answer to show how you could better form JSON from an object/array definition like you have. That might look like this:
// build data structure first
// in this example we are using javascript array and object literal notation.
var objArray = [
{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}
];
// now that your data structure is built, encoded it to JSON
var JsonString = JSON.stringify(objArray);
Now if you want to work with JSON-encoded data, You just do the opposite:
var newObjArray = JSON.parse(JsonString);
These are really the only two commands you should ever use in javascript when encoding/decoding JSON. You should not try to manually build or modify JSON strings, unless you have a very specific reason to do so.

How does JSON.parse() work?

I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.

Generating nodes using ruby and displaying them with javascript error

So Im trying to extract nodes from my database (by going through it recursively) and then displaying the json code i have to a javascript library. The problem is that the library is not identifying the json array output because it has extra quotation marks and a slash (/). Here is the code:
data = {
"nodes":
"\"User1:{'color':'green','shape':'dot','label':'You'},
User2:{'color':'green','shape':'dot','label':'You'},
User3:{'color':'green','shape':'dot','label':'You'}\""
,"edges":{}};
And I want it to look something like this:
var data = {
"nodes":{
"You":{'color':'green','shape':'dot','label':'You'},
Ben:{'color':'black','shape':'dot','label':'Ben'},
David:{'color':'black','shape':'dot','label':'David'}
},
"edges":{
You:{ Ben:{}, David:{} },
Ben:{ David:{}}
}
};
In my user_controller I am using this:
def make_json(node, string = "")
node[1].each do |n|
string += node[0] + "{'color':'green','shape':'dot','label':'You'},"
return make_json(n, string )
end
return string + node[0] + "{'color':'green','shape':'dot','label':'You'}"
end
And finally, this:
#data = {}
#data['nodes'] = make_json(#user_tree[0]).to_json
#data['edges'] = {}
I tried using the replace method, but the data variable doesnt seem to be a String so I can't just replace the quotation marks. I'd appreciate any sort of help.
Thanks!
The reason for the extra \" in the output is that you are calling to_json on the return value from your make_json method which is a string.
Its hard to see exactly what you are trying to do in make_json, but assuming that you want to use the output as a value in your #data hash and then convert that to json I think you would be better off having make_json build a hash and return that. Generally when returning a JSON response the easiest solution is to build a data structure out of Ruby hashes and arrays and then call to_json on that. Here is a much simplified example (I don't know what the #user_tree is so I don't understand the recursive step but I hope this gives you the general idea):
def make_json(node, hash = {})
node[1].each do |n|
hash[n[0]] = {:color => 'green', :shape => 'dot', :label => n[0]}
end
hash
end
If you try to construct the JSON string yourself it is easy to trip up. The output that you say you are aiming for is not valid JSON though it may be valid JavaScript. Strings need to be wrapped in double quotes, e.g.
"Ben": {"color": "black", "shape": "dot", "label": "Ben"}
rather than:
Ben:{'color':'black','shape':'dot','label':'Ben'}

How to store a json array with .NET?

I Have a json array like
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]
How can i pass(to the backend) and store(in db) that javascript object with asp.net??
EDIT:
OK to make it clearer, in some page, i got a javascript object
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
, how can i pass it to some handler (like using
`$.post({url:"handler.ashx", data:array})
??), then in backend how can i save it into database or load this array later??
OR:
I'll appreciate it if u teach me how to convert
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
into:
var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]';
EDIT2:
Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
You have several options when dealing with JSON on .NET
You can simply keep the array as is in the DB and retrieve it as is and use it
You can parse it into an Object using JSON.NET Library
for example on the 2nd case you simple use the JSON.NET method:
Newtonsoft.Json.Converters.KeyValuePairConverter
Or be fancy and use a Custom Deserialize as it's really easy to pass to and from JSON.
Let's imagine that you are posting something like this:
$.post("myForm.aspx",
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}],
function() {
// all done.
});
This will be converted to A,B,C when requesting the data using Request.Form["name"] or simply Request["name"] so you should change all the naming convention first and then you can simple use Request["nameA"], Request["nameB"], etc...
You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.
The best way to do this is to de-serialize the json into object and save it to db as records.
Check JSON.NET library http://json.codeplex.com/
public class MyObj
{
public string name{get;set;}
public string value{get;set;}
}
void Main()
{
string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]";
IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json);
foreach(MyObj o in arr)
{
//add each object to db...
Console.WriteLine(o.name+":"+o.value);
}
}
Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.

Categories

Resources