I want to parse this format of data by JSON --- {"A":"[[a,b],[c,d]]"} . I want to retrieve values a,b,c,d separately.
IF I DO alert(JSON.stringify(data)); This shows me proper response.
I Tried following things to parse but didnt work.
alert(data.A[0]);
alert(data.[0]);
alert(data.A);
data is JSONOBJECT HERE.
1 and 2 does not work at all.
3 at least show me undefined. Please someone tell me how i can retrieve this format.
Try this and check console
data = {"A":"[[a,b],[c,d]]"} ;
console.log(data.A);
"[[a,b],[c,d]]"
This is not javascript object . Its a string
If you want to use it as a javascript collection
Use as follows
data = {"A":[["a","b"],["c","d"]]} ;
console.log(data.A[0]); //=>["a", "b"]
console.log(data.A[0]); //=>["c","d"]
change your json object by data={A:[['a','b'],['c','d']]} . you can now access data.A[0][0], data.A[0][1]...
Related
I am trying to figure out how to take an array of arrays and convert it to a json string to return via a REST api.
My server gets records from a database. Each record is in the form:
{"user":"some name","age":number}
I need to return the data in json format so that the REST specification is valid.
Sometimes I get a single record to return other times I get multiple records.
Below is a sample script I am using to test the syntax for converting into json format.
var resultSet = [];
resultSet.push({"user":"John Doe","age":43});
resultSet.push({"user":"Jane doe","age":29});
var myJson = JSON.parse(resultSet);
When I run this code using nodejs I get the following error:
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Any suggestions would be very appreciated.
JSON.parse expects a string. You are passing an Array.
This works because the input is a string:
JSON.parse('[{"foo": "bar"}]')
This doesn't work because the input is an Array:
JSON.parse([{"foo": "bar"}])
Are you trying to return an Array or a string? If you are trying to return a string, then you should use JSON.stringify like this:
JSON.stringify([{"foo": "bar"}])
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 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.
I'm attempting to parse a JSON string with nested objects received in the response of a post request. After running JSON.parse(responseText), the result is in the following format:
[{
"atco":"43000156407",
"location":{
"longitude":"-1.7876500000000000",
"latitude":"52.4147200000000000","
timestamp":"2013-03-19 11:30:00"
},
"name":"Solihull Station Interchange",
"road":"STATION APPROACH",
"direction":"NA",
"locality":"Solihull",
"town":"Solihull"}, ...
I thought I would then be able pull values out using the following as an example, but all I get is undefined.
var atco = json[0].atco;
I've also tried json[0][0] but that returns an individual character from the JSON ([) . Does this indicate the JSON hasn't parsed correctly, or is this expected behaviour and I'm just referencing incorrectly?
This means that your JSON is being double encoded. Make sure you only encode it once on the server.
As proof, after you've parsed it, parse it again.
var parsed = JSON.parse(resposneText);
var parsed2 = JSON.parse(parsed);
alert(parsed2.atco);
Either that, or you're parsing it but then trying to select the data from the original string. This would obviously not work.
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.