Reputation: 33
I am returning a List of JSON items back from the front end. It current looks like:
[
"[{ "_id" : ObjectId("5cbcd80e0c5c9f1dfc8bf2f3"), "price" : "$1,
399.00", "name" : "AlienwareGamingPCDesktopAuroraR7-8thGenIntelCorei7-8700,
16GBDDR4Memory,
2TBHardDrive+32GBIntelOptane,
?NVIDIAGeForceGTX10808GBGDDR5X,
Windows1064bit\", "url" : "https: //www.amazon.com/gp/product/B076BHG74V/ref=s9_acsd_zwish_hd_bw_b2N0U_>c_x_w?pf_rd_m=ATVPDKIKX0DER&pf_rd_s=merchandised-search-11&pf_rd_r=TW0CMS0QN07XT2BM838T&pf_rd_t=101&pf_rd_p=62f4ca32-9706-51c1-a1d1-9f7214564c34&pf_rd_i=565098\", "description" : "ThenewAlienwareAuroraisamid-towerdesktopwithaMicroATXmotherboardandisalsooursmallestdual-graphicscapabledesktopandhasmoretool-lessfeaturesthananypreviousAlienwaredesktopsuchas: tool-lessgraphics,
expansioncards,
hard>drives,
andmemory.", "keywords" : ["computer"] }]"
]
When displaying the results with: console.log(results[0]), it displays the whole object. When doing console.log(results[0].name) or console.log(results[0].name) I get a undefined error. There is current only one object in the list, but for future queries there will be more. Any ideas on how to access individual elements?
What the code in the frontend looks like:
.then(response => {
this.amazonItems = response.data;
console.log(this.amazonItems[0]);
Query of MongoDB:
var result = collection.Find(filter).Sort(sort).ToList().ToJson();
Serialization:
List<string> returnResult = new List<string>();
returnResult.Add(_sm.SearchAmazonQuery(searchQuery, _db));
response.Content = new StringContent(JsonConvert.SerializeObject(returnResult), System.Text.Encoding.UTF8, "application/json");
response.StatusCode = HttpStatusCode.OK;
return response;
Console output: console
Upvotes: 0
Views: 95
Reputation: 164969
I don't really know much about your server-side code (guessing C#) but, assuming
_sm.SearchAmazonQuery(searchQuery, _db)
returns the result of
var result = collection.Find(filter).Sort(sort).ToList().ToJson();
which appears to already be a JSON string, I suspect you just want
response.Content = new StringContent(_sm.SearchAmazonQuery(searchQuery, _db),
System.Text.Encoding.UTF8, "application/json");
This means your response.data
will be an array of objects, not an array of JSON strings.
.then(response => {
this.amazonItems = response.data
console.log(this.amazonItems[0])
// 👉 {_id: "5cbcd80e0c5c9f1dfc8bf2f3", price: "$1,399.00", ...
})
Upvotes: 0
Reputation: 6755
Try parsing, I think it is in stringify mode.
.then(response => {
this.amazonItems = response.data;
console.log(JSON.parse(this.amazonItems[0]));
Upvotes: 1
Reputation: 10484
It looks like it’s stringified, try JSON.parse(results[0]), also that’s some weird syntax ObjectId(‘asdajdjsja’)
Upvotes: 0