Hi everyone I have some problems with angular, I made a request in $http so i have a JSON like:
{"y":"1","a":"0"}
and I want to convert it to an array like
{y:1, a:0}
I'd already tried whit angular.fromJson(myData) but it doesnt works
Hope you´ll help me because Im a begginer
This is just a hint/suggestion, something you might overlooked. It is hard to understand your question, clarify if this is not what you are looking for.
Maybe for some reason you got "{"y":"1","a":"0"}" back, which is a string.
If you need to get a JSON object from it then use JSON.parse(string) function.
Use this method is used to convert json string response to an array, object, number
var temp = [];
temp = angular.fromJson(json);
console.log(temp);
This function will convert and return
https://docs.angularjs.org/api/ng/function/angular.fromJson
The only difference between the object that you have after parsing the JSON and the object that you want is that the string values need to be number values.
Loop though the keys and convert the values:
for (key in obj) obj[key] = parseInt(obj[key], 10);
Related
I get the following GeoJSON from my server:
[{"st_asgeojson":"{\"type\":\"Point\",\"coordinates\":[-180081.82,5279725.36]}"}]
How can I get the coordinates field? I have the GeoJSON stored in a geovar variable
I tried with geovar["st_asgeojson"].coordinates,geovar[0]["st_asgeojson"].coordinates, geovar[0]["st_asgeojson"]["coordinates"] but they seem to be undefined.
Any idea? I know it's pretty simple but I'm stuck with it. Thanks.
The value of "st_asgeojson" now is a string. You need to parse it to JSON before access it. Using map to loop through and parse the value of "st_asgeojson" with JSON.parse
const geovar = [{"st_asgeojson":"{\"type\":\"Point\",\"coordinates\":[-180081.82,5279725.36]}"}]
const rs = geovar.map(e => {
e["st_asgeojson"] = JSON.parse(e["st_asgeojson"])
return e
})
console.log(rs[0]["st_asgeojson"]["coordinates"])
console.log(rs)
Ok, I finally solved this way:
[{"st_asgeojson":"{\"type\":\"Point\",\"coordinates\":[-180081.82,5279725.36]}"}]
is a JSON with a GeoJSON inside. Before parsing the GeoJSON I had to get the GeoJSON string from an already parsed JSON. The only neccesary instructions were:
var obj = JSON.parse(geovar[0]["st_asgeojson"]);
var coordinates = obj.coordinates;
Which is you are getting from your server that is JSON String data.If you want to parse then first Make JSON using JSON.stringify() function. Hope that will solve your issue. After that you can easily parse your data as you want.
No one really answered this question but how on earth can one use this JSON return data from a php/mysql direct using JavaScript?
Here is the return data once i used JSON.parse and saved it to the Javascript variable obj
[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]
I've tried the simple obj.stuname but it returns only an undefined i've tried many times to understand it but i can't seem to use this array at all.
Could anyone help on this?
I've also tried the reObj = {"stu":obj}; style but then it only returns an [object Object]
so please someone elaborate on this?
obj is a json array, so you have to access an element using its index.
Also, you have to use JSON.parse in order to turn a string of json text to a Javascript object.
Try this:
var stuname=obj[0].stuname;
var obj='[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]';
var objParsed=JSON.parse(obj);
console.log(objParsed[0].stuname);
If you want to iterate array, use forEach method.
var obj='[{"stuid":"10-00002","stuname":"Meratis, Velino","stucourse":"Arts","stustat":"0","stulyear":"4","stulog":"feb 16 2017"},{"stuid":"10-00003","stuname":"Melker, Alana","stucourse":"Wilderness","stustat":"1","stulyear":"5","stulog":"feb 16 2017"}]';
var objParsed=JSON.parse(obj);
objParsed.forEach(function(item){
console.log(item.stuname);
});
If you are getting this response from php via ajax.
Be sure to use dataType as json to get json type response not string.
Otherwise you need to parse json data like this
obj = JSON.parse(jsonStrFromPhp);
Then you can fetch data as obj.stuname or obj[0].stuname depends how you returned from php like this {"stu":obj} or like this [{"stu":obj}]
while i was having a migraine... of why my code was wrong it turned out that even though the obj = JSON.parse(jsonStrFromPhp); returned only an [object Object],[object Object] javascript can actually understand that shins and returned my variable... how confusing.
I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference
I'm new to jQuery and just playing for fun. I have some code that I want to try to modify for my needs but the current js file is getting its data from google spreadsheets and then returning each item as objects. I don't use json to pass data from my server to jQuery so I'm wondering how I can convert json to objects.
The current way its doing it is(tabletop is the name of their js program that gets data from google docs):
Tabletop.init({
key: timelineConfig.key,
callback: setupTimeline,
wanted: [timelineConfig.sheetName],
postProcess: function(el){
//alert(el['photourl']);
el['timestamp'] = Date.parse(el['date']);
el['display_date'] = el['displaydate'];
el['read_more_url'] = el['readmoreurl'];
el['photo_url'] = el['photourl'];
}
});
I have added alerts all over the file and I think this is the area that gets the data and passes it on. I was thinking of trying to replace items in their object with objects from my json and see if it changes anything, but I'm unsure. Typrically I pass individual items via json,hashmaps, and lists, not sure how it works with objects or how to access objects(I simply call url's that I create for the requests, $("#user-history").load("/cooltimeline/{{ user.id }}");). But where do I start if I want to turn json data into objects?
If it helps, here's the demo of what I'm trying to do(but by having it use json data).
p.s. I'm really looking for the logic of how to complete what I'm trying to do and perhaps some ideas I'm missing so I can google them and learn.
Use use function JSON.parse(json) :) Or jQuery.parseJSON(json)
var json = '{"a":2}';
var object = JSON.parse(json);
alert(object.a);
You should see alert with message: 2
I don't realy know if I understand your comment, but maybe you want just do this:
postProcess: function(el){ //here el is JSON string
el = JSON.parse(el); // now el is an object
el.timestamp = Date.parse(el.date);
el.display_date = el.displaydate;
el.read_more_url = el.readmoreurl;
el.photo_url = el.photourl;
return el;
}
Btw. you do not need to use brackets on know property names without not standard names:
el['timestamp'] === el.timestamp
It will be easier if you paste your JSON
My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.
I've tried:
var a = msg.d[1].key
With no success of course.
This is the returned string:
"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"
The string was extracted using FireBug after watching the msg.d.
Need your help in solving this.
msg[1].key
Assuming that the name of that array is msg. I'm not sure what you are using .d for.
If msg.d is a string representing an array, use JSON.parse.
JSON.parse(msg.d)[1].key
You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.
This works as expected for me.
var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;
What is msg in the example above? Need more info to help.
If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.