Getting return value from JavaScript in UIWebView - javascript

I want to fetch JavaScript return value in my ViewController,
The problem is that, if there is small amount of data like String, I'm getting it.
But if there is large data like JSON object,It's showing nil.
When I call same JS function in Safari > Develop > iOS simulator, it's giving JSON object after 1-2 secs.
Here is my code:
var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_small_string()")
println(value) //Printing value
but this prints nil,
var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_JSON()")
println(value) //Printing nil
anyone knows how can I fetch big size JS return value in iOS object?

This solve my problem,
var value = IBwebView.stringByEvaluatingJavaScriptFromString("get_JSON()")
var err:NSError?
var obj:AnyObject? = NSJSONSerialization.JSONObjectWithData(value!.dataUsingEncoding(NSUTF8StringEncoding)!, options:nil, error:&err)
if let items = obj as? NSDictionary {
var data1:String = items.objectForKey("data1") as? String
var data2:String = items.objectForKey("data2") as? String
var data3:String = items.objectForKey("data3") as? String
}

As soon as you will return an object it will not work, what you can try instead is to return a stringified version of your object
JSON.stringify(yourObject);
And parse this string on the native side.

If your java script method "get_JSON()" return more than 10 MB data then its not allowed by stringByEvaluatingJavaScriptFromString method.
Or If it take more than 10 sec to process output ,in that case you will be get nil value as output.

Related

From JSON to Actionscript

Good Day,
is it possible to convert an object to an Actioscript model in Javascript ?
I have this:
const user = [{"id":"1","name":"Doe","firstname":"John","tel":"1112223333"}];
I would like to have this:
const user = [{id:1,name:"Doe",firstname:"John",tel:1112223333}];
When I use user.replace(/"/g,""); I have the error:
user.replace is not a function
But this is where I'm stuck. I don't know how to do it if I can't use replace.
To put you in context, the object is fetched via ajax and PHP by doing echo json_encode($to_encode);
Thank You for your help! :)
Its a JSON.parse()
Updated
convert the string to number
const user ='[{"id":"1","name":"Doe","firstname":"John","tel":"1112223333"}]';
var res =JSON.parse(user)
res.forEach(function(a){ //convert the string to number
Object.keys(a).forEach(function(key){
a[key] = Number(a[key])||a[key]
})
})
console.log(res)
Check you broswer console.log F12 is showen like this

How to store and retrieve JSON data into local storage?

I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}

Get values from JSON returned data

So I have a function that makes an ajax call and returns a json string. I am having trouble trying to access the values that I need, below is my code of what I have and a few examples of what I have tried.
s.search().then(function (specials) {
var returnJSON = JSON.parse(specials[0]);
var x = returnJSON.location.x;
var y = returnJSON.location.y;
});
When I check the dev tools I'm getting the following error.
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Here is the the JSON returned value after I stringify it.
[{"feature":{"geometry":{"type":"point","x":-82.9172080701955,"y":42.55426092899978,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Postal","Match_addr":"48035, Clinton Township, Michigan","StAddr":"","City":"Clinton Township","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.922209,"ymin":42.549261,"xmax":-82.912209,"ymax":42.559261,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"48035, Clinton Township, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.03589825899667,"y":44.826904141314174,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.085899,"ymin":44.776904,"xmax":-83.985899,"ymax":44.876904,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.93987906956261,"y":42.065412162742234,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-83.98988,"ymin":42.015412,"xmax":-83.88988,"ymax":42.115412,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-82.93354923650725,"y":42.60054198222781,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.98355,"ymin":42.550542,"xmax":-82.88355,"ymax":42.650542,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.97095926895429,"y":42.07240087260328,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.02096,"ymin":42.022401,"xmax":-83.92096,"ymax":42.122401,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.6015125489642,"y":42.943655651388326,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"SubAdmin","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.839514,"ymin":42.705656,"xmax":-84.363514,"ymax":43.181656,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"}]
I am trying to access candidates location x value and y value.
There are some Strings in your JSON on separate lines. When you copy and paste your JSON in a linter (e.g.: json linter), you will see the errors.
EDIT:
You edited your question so you are now using valid JSON.
There is no need to parse your JSON when you already have valid JSON. You can just select the correct keys. Looking at your JSON, you can select your x and y like this:
var returnJSON = specials[0];
var x = returnJSON.feature.geometry.x;
var y = returnJSON.feature.geometry.y;
Checkout this codepen for an example.
You don't need to "parse" JSON returned from a service usually. It is already a Javascript object in the then callback.
s.search().then(function (specials) {
var firstItem = specials[0];
var x = firstItem.location.x;
var y = firstItem.location.y;
});
It should be noted, however, that the first item that comes back in your array of specials does not have a property location accoring to the JSON example you posted.
Perhaps you were after firstItem.feature.geometry.x, but im not sure.

converting string to integer in Javascript

I am reading some values from an xml file using JavaScript. Since it is a string, i need to convert it to integer and perform some calculations.
For reading the data from XML file I use this code:
var pop = JSON.stringify(feature.attributes.Total_Pop.value);
which works fine. later I use the following code to convert it to integer:
var popint = parseInt(pop);
This also works fine. But later when I use it to do some math, it returns NAN.
the code I use for Math operation is:
var pop6 = Math.ceil(popint / 30);
What am I doing wrong? any suggestions?
Don't stringify -- just use var pop = feature.attributes.Total_Pop.value;. Calling JSON.stringify wraps the string in extra quotation marks.
var pop = "123"; // "123"
var popint = parseInt(pop); // 123
Vs:
var pop = JSON.stringify("123"); // ""123""
var popint = parseInt(pop); // NaN

Unexpected token , - asp value showing as undefined

i am trying to upload some data from vb.net to asp.net using array json.
my code:
<script type="text/javascript">
$(function() {
var a = $("#hidden").val();
var array = JSON.parse(a);
however, when i debugged this on the browser, "a" and "array" was showing as undefined. even though in the code behind it was showing the value..
after further investigation, i found out that if it is like this it works:
var a = "[1, 2, 3]";
var array = JSON.parse(a);
note it is showing as a string, however when i take the string of:
var a = [1, 2, 3];
var array = JSON.parse(a);
it says its undefined - Uncaught SyntaxError: Unexpected token, am guessing its to do with the JSON.
now back to my code and my error:
code behind (vb)
Dim array As New ArrayList
For Each row In ChartData.Rows
array.Add(row("Day"))
Next row
Dim serializer As New JavaScriptSerializer()
Dim arrayJson As String = serializer.Serialize(array)
hidden.Value = arrayJson
and code in asp.
<asp:HiddenField ID="hidden" runat="server" />
var a = $("#hidden").val();
var array = JSON.parse(a);
my problem is, why is it showing undefined! what have i done wrong.
thanks
on asp.net the rendered id is not the one you use on code behind, to get it on page you need to use the ClientID as:
var a = $("#<%=hidden.ClientID%>").val();
Json.parse takes a string and returns a json object. It needs a valid json input in order to parse the input, this is a string. You can also use the JSON.stringify method before call parse to ensure passing an input as a string.

Categories