Can't access an element in JSON array - javascript

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.

Related

Cant convert JSON to array in Angular.js

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

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

Show Json Object In TextBox

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

Parsing Json document. Can you explain why key giving values? Also help parse my list better?

I am teaching myself jquery and json for work. I have been making great progress, but now got myself very confused. My ultimate goal is to be able to parse json from a text file I have and then store them as javascript objects so I can do more stuff with it.
This is what I have done. I have the following data in json format (created from a java class I wrote). Please note that data.json looks like this:
{"Time": 15,
"Distance": 20,
"Position":[{"x":5,"y":10},
{"x":15,"y":20}]}
I formatted the above in this question to be easier to read by being on separate lines, but the raw file contains it all on one line.
I used the following code in a script:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key,val)
{
alert(val.Time);
alert(val.Distance);
alert(val.Position);
});
});
But what it outputs is three "undefined" alerts. Why? My ultimate goal is to store Time, Distance, and the Position as javascript objects so I can draw them on a graph I made in html. However, I am obviously no way close to that because my alerts are not reading/parsing json objects right.
So I changed it to as follows, on a hunch:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key,val)
{
alert(key.Time);
alert(key.Distance);
alert(key.Position);
});
});
Well, these is mostly promising in that I get the following alerts:
Alert 1 Output: 15,
Alert 2 Output: 20,
Alert 3 Output: [Object Object], [Object Object]
Okay, I am closer, but now very confused. Shouldn't the key be giving me alert output "Time", "Distance", and "Position" and val be "15", "20", and "[Object Object], [Object Object]". I thought json kind of works like a hashtable. Hmmmm.
Also, do I need to do a .each(key, val) to parse my list called Position? Because obviously Object Object is not going to help me much. I basically want to save this list Position as a javascript obj like
myList = [[5, 10], [15,20]]
Anyway, that is my thinking. I thank you for your time. I will upvote anyone who replies and helps me out. This is important to me.
Regards,
GeekyOmega
I'm not sure what you're trying to do with your function(key,val) { ... }, but this isn't how jQuery's getJSON works at all. The callback function for getJSON takes three parameters, data, textStatus and jqXHR. I suspect you will find that the data parameter is essentially the javascript object you wanted to build, except with fields 'x' and 'y' rather than each nested array. To get the data out, I'd do something like:
for (var i = 0; i < data.Position.length; i ++)
do_something_with (data.Position[i].x, data.Position[i].y);
key and val as you have them are misnamed. The first parameter to the $.getJSON() callback is the JSON object. See the API Doc example where the callback function is just passed a parameter called data.
[Object Object] is the default toString() for objects in javascript. To get the values of your object array, you can iterate data.Position and access the x and y properties of each object in the array.
Edit to respond to your comment:
You could always change the Position property in your JSON to be generated as an array of arrays instead of an array of objects.
Or, on the client side, you could do something like this:
var points = [];
$.each(data.Position, function(item) {
points.push([item.x, item.y]);
});
Re-read your key names. Words like route and travelTime appear in your code but not in your JSON.
Try this:
$(document).ready(function(){
console.log("ready!");
$.getJSON('data.json', function(key)
{
console.log(key.Time);
console.log(key.Distance);
console.log(key.Position[0]);
});
});
when you create a class user javascript,you can write var pepole={name:"smith",code:"YQ001",println:function(code,name){document.write(this.name+":"+this.code+"<br/>")}};,json is a class for javascript,but there is no method it's only attribute

Retrieve JSON Array element value

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.

Categories