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