Reputation: 331
I am not very familiar with Javascript and Postmen tests, so I might be overlooking something completely. Anyway I have a simple API that queries a mongo DB and returns a 'Student'.
The raw response is:
"{\"_id\": \"63e8b7406e2fd8d4555554be\",
\"first_name\": \"DeJorr\",
\"gradeRecords\": [{\"grade\": 6.027456183070403,
\"subject_name\": \"subject_name\"},
{\"grade\": 6.027456183070403, \"subject_name\": \"subject_name\"}],
\"last_name\": \"ThisisALastname\"}"
Here is my postman test:
tests["Status code is 200"] = responseCode.code === 200;
var jsonData = JSON.parse(responseBody);
first_name = "DeJorr"
tests["Type: "+typeof jsonData] = jsonData.first_name == first_name;
tests["JSONDATA: "+jsonData] = jsonData.first_name == first_name;
tests["First Name: "+jsonData.first_name] = jsonData.first_name == first_name;
So in the logs of that failing tests, see screenshot, we can see that the 'jsonData' var is a string instead of an object. That is why the rest is failing.
Any ideas as to why JSON.parse(responseBody) does not produce an object?
If i copy the raw response to a JavaScript REPL all works fine..
EDIT:
Server side code, the dumps function is from BSON.json_util. The DB queried is a mongoDB.
def get_by_id(student_id=None, subject=None):
try:
student = collection.find_one({"_id": ObjectId(student_id)})
if not student:
return 'not found', 404
except:
# Invalid ID formats simply return not found
log.warning("Invalid ID")
return 'not found', 404
# Works with double JSON parse client side:
return dumps(student)
# Works normally client side:
student["_id"] = str(student["_id"])
return student
Upvotes: 0
Views: 683
Reputation: 16666
If the raw response is
"{\"_id\": \"63e8b7406e2fd8d4555554be\",
\"first_name\": \"DeJorr\",
\"gradeRecords\": [{\"grade\": 6.027456183070403,
\"subject_name\": \"subject_name\"},
{\"grade\": 6.027456183070403, \"subject_name\": \"subject_name\"}],
\"last_name\": \"ThisisALastname\"}"
then it is indeed the JSON representation of another string, that is, of the string
{"_id": "63e8b7406e2fd8d4555554be",
"first_name": "DeJorr",
"gradeRecords": [{"grade": 6.027456183070403,
"subject_name": "subject_name"},
{"grade": 6.027456183070403, "subject_name": "subject_name"}],
"last_name": "ThisisALastname"}
and JSON.parse
of this latter string gives you a Javascript object. So you would need
var jsonData = JSON.parse(JSON.parse(responseBody));
But I would expect a JSON response from the server, so it should already return the latter string. Can you share the server-side code?
Upvotes: 2