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.
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"}])
I'm trying to replace the angularjs POST query with standalone JSON response string.
When angular GET / POST queries returns a response automatically converted to JSON and the code was working like charm.
Now, I'm trying to have the json response stored as a javascript string variable in the controller and then trying to parse it using JSON.stringify() and subsequently using JSON.parse().
There is no error but the resulting json object's member variables can't be accessed using the . operator
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
var resultString = JSON.stringify(staticData);
$scope.staticTestData = JSON.parse(resultString);
console.log($scope.staticTestData.masterJobs); // this displays 'undefined'
Controller function with the large JSON is available here.
You already have a string, so there is no need to use JSON.stringify.
Just use the following code:
var staticData = '{"someKey":"someValue", "masterJobs":[]}'; //very large json string.
$scope.staticTestData = JSON.parse(staticData);
console.log($scope.staticTestData.masterJobs);
is there anyway i can get this malformed json format which is odd i have no control over this json manually so i need to get this data and manipulate it with rxjs observable from http get
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
{
"firstNm": "Ronald",
"lastNm": "Mandez",
"avatarImage": "https://randomuser.me/api/portraits/men/74.jpg"
}
I tried with your JSON in the console and this seems to work. In the map function I've used you can probably implement more generic replacement methods to alter the strings, but it works for this example.
function fixBadJSON(response){
let badJSON = JSON.stringify(response); // added this edit in case you don't know how to get the response to a string
let arr = badJSON.split('}\n'); // Looks like the JSON elements are split by linefeeds preceded by closing bracket, make into arr length of 3
let fixedArr = arr.map((item)=>{ // map the array to another, replace the comma at the end of the avatarImage key. elements in array should be proper JSON
if(item[item.length] != '}') item += '}'; //put the brackets back at thend of the string if they got taken out in the split, probably a better way to handle this logic with regex etc
return item.replace('jpg",','jpg"')
});
let parsedJSON = JSON.parse(JSON.stringify(fixedArr));
return parsedJSON
}
Take the JSON data you've posted up there and copy it to a variable as a string and test the function, it will return a properly formatted array of JSON data.
Call that when you get a response from your service to transform the data. As far as the observable chains and any async issues you might be seeing those are separate things. This function is just designed to convert your malformed JSON.
{
"content": "{\"text\":\"Executing NodeDatasetFileOrDirectoryCSV : 1\",\"id\":1,\"name\":\"CSV\",\"type\":\"text\"}"
}
\ tag is getting appended after everything.
I want to access the type field. But i am not able to even after content.type because of the \ appended after every element. How to remove this ?
You're response is coming down as a valid JSON object, but the content property holds a value that is a JSON string, not a JSON object. You can either fix it on your server-side however you are constructing your response, or you can use JSON.parse to parse the content JSON string into a full-fledged object in JavaScript after you get your response.
The latter would be something like this:
var response = {"content": "{\"text\":\"Executing NodeDatasetFileOrDirectoryCSV : 1\",\"id\":1,\"name\":\"CSV\",\"type\":\"text\"}" };
response.content = JSON.parse(response.content);
console.log(response.content.type);
Use JSON.parse() to get the JSON object from the string and then get the values using keys.
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.