From JSON to Actionscript - javascript

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

Related

How to modify text in Javascript

I made a script to retrieve data from an API and show it in HTML.
The problem is that the API answers with something like that
[{"seen":"2021-08-24 04:13:51"}]
And I want the user to see something like
2021-08-24 04:13:51
How can i modify this text inside of javascript? (The output is variable but the number of characters is always the same, idk if this is a useful info...)
What you have to do is set innerText value from the JSON. You can access the value using response[0].seen
const response = [{"seen":"2021-08-24 04:13:51"}];
console.log(response[0].seen);
document.getElementById('lastupdatedon').innerText = response[0].seen;
<p id="lastupdatedon"></p>
The server is returning data in json format, you need to parse the response to a javascript object and then you can use the value as you want
const theServerResponse = '[{"seen":"2021-08-24 04:13:51"}]'
const parsedResponse = JSON.parse(theServerResponse)
//At this point you can get that value
parsedResponse[0].seen
Use below script
var fromAPI='[{"seen":"2021-08-24 04:13:51"}]';
var data=JSON.parse(fromAPI);
if(data!=null && data.length>0)
{
document.getElementById('lastupdatedon').innerText = data[0].seen;
}
HTML
<h3 id="lastupdatedon"></h3>
Do not forget to check for nulls, index is greater than 0. IF server doesnt return data then your app will throw an error of undefined.

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);
}

Getting return value from JavaScript in UIWebView

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.

putting json into javascript variable

I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers

javascript convert string to multi array array

I have an initial array (users) with multiple (string and numeric) arrays therein:
var users = [
['User: 10792 - Jack',45.7546,-117.807,2,'/res/smR11.gif'], ['User: 11248 - John',38.0867,131.976,3,'/res/smR08.gif']
];
I have a string of data from our server in the current form of:
newData = "['User: 18469 - Gary',-33.9399732539481,151.164383805489,3,'/res/markerw.gif'],['User: 10020 - Robert',40.6437563454472,-73.7593346140851,6,'/res/smR10.gif']";
I erase all existing data with users.length = 0;
I then need to insert the newData into the users array.
NOTE: I can obviously modify the server data into any other format
that would be more suitable.
Any help would be greatly appreciated.
try something like this
var users = JSON.parse(newData);
Your newData string looks very similar to the javascript above it. How about this...
users = eval('[' + newData + ']');
[EDIT]
As Bergi, rajeshkakawat and StephenJames pointed out, eval will work but is less secure.
See: JSON.parse vs. eval()

Categories