JSON getting object inside a JSON - javascript

I am trying to get an object from inside a JSON but I can't. It only gives me undefined.
But when I check the result on the console it gives me the right results.
Here is my JSON
{
users: [
{
userID: "151",
userFirstname: "first",
userMiddlename: "middle",
userLastname: "latname",
userAddress: "qewasd",
userContactNumber: "123456",
userRole: "role",
userName: "user",
userPassword: "pass",
userEmail: "test#gmail.com",
userPitch: "Very good",
userExperience: "5",
userFirm: "Sample",
userRollNo: "0"
}
]
}
and here is my javascript
$(document).ready(function () {
$.getJSON('http://batz.web/Sandbox/details.php?userID=151', function (results){
document.getElementById("title").innerHTML = results.userID;
console.log(results);
});
});

Ok look at your json, userID is not a direct child of the results object, which means It will always return null every time you try to get the value of undefined field
You first need to get the array's content with the key(left side of full colon), as the array is in "users" field(or key) ,userId is not still in the array's field, so you gotta point with an index(e.g,0,1,2,...) to get the object which contain userID
...
document.getElementById("title").innerHTML = results.users[0].userId;
...
Here is the fiddle

Related

How to add within an array information using findOneAndUpdate without deleting information that was previously contained [duplicate]

I am working on an express js application where I need to update a nested array.
1) Schema :
//Creating a mongoose schema
var userSchema = mongoose.Schema({
_id: {type: String, required:true},
name: String,
sensors: [{
sensor_name: {type: String, required:true},
measurements: [{time: String}]
}] });
2)
Here is the code snippet and explanation is below:
router.route('/sensors_update/:_id/:sensor_name/')
.post(function (req, res) {
User.findOneAndUpdate({_id:req.body._id}, {$push: {"sensors" :
{"sensor_name" : req.body.sensor_name , "measurements.0.time": req.body.time } } },
{new:true},function(err, newSensor) {
if (err)
res.send(err);
res.send(newSensor)
}); });
I am able to successfully update a value to the measurements array using the findOneAndUpdate with push technique but I'm failing when I try to add multiple measurements to the sensors array.
Here is current json I get if I get when I post a second measurement to the sensors array :
{
"_id": "Manasa",
"name": "Manasa Sub",
"__v": 0,
"sensors": [
{
"sensor_name": "ras",
"_id": "57da0a4bf3884d1fb2234c74",
"measurements": [
{
"time": "8:00"
}
]
},
{
"sensor_name": "ras",
"_id": "57da0a68f3884d1fb2234c75",
"measurements": [
{
"time": "9:00"
}
]
}]}
But the right format I want is posting multiple measurements with the sensors array like this :
Right JSON format would be :
{
"_id" : "Manasa",
"name" : "Manasa Sub",
"sensors" : [
{
"sensor_name" : "ras",
"_id" : ObjectId("57da0a4bf3884d1fb2234c74"),
"measurements" : [
{
"time" : "8:00"
}
],
"measurements" : [
{
"time" : "9:00"
}
]
}],
"__v" : 0 }
Please suggest some ideas regarding this. Thanks in advance.
You might want to rethink your data model. As it is currently, you cannot accomplish what you want. The sensors field refers to an array. In the ideal document format that you have provided, you have a single object inside that array. Then inside that object, you have two fields with the exact same key. In a JSON object, or mongo document in this context, you can't have duplicate keys within the same object.
It's not clear exactly what you're looking for here, but perhaps it would be best to go for something like this:
{
"_id" : "Manasa",
"name" : "Manasa Sub",
"sensors" : [
{
"sensor_name" : "ras",
"_id" : ObjectId("57da0a4bf3884d1fb2234c74"),
"measurements" : [
{
"time" : "8:00"
},
{
"time" : "9:00"
}
]
},
{
// next sensor in the sensors array with similar format
"_id": "",
"name": "",
"measurements": []
}],
}
If this is what you want, then you can try this:
User.findOneAndUpdate(
{ _id:req.body._id "sensors.sensor_name": req.body.sensor_name },
{ $push: { "sensors.0.measurements": { "time": req.body.time } } }
);
And as a side note, if you're only ever going to store a single string in each object in the measurements array, you might want to just store the actual values instead of the whole object { time: "value" }. You might find the data easier to handle this way.
Instead of hardcoding the index of the array it is possible to use identifier and positional operator $.
Example:
User.findOneAndUpdate(
{ _id: "Manasa" },
{ $push: { "sensors.$[outer].measurements": { "time": req.body.time } } }
{ "arrayFilters:" [{"outer._id": ObjectId("57da0a4bf3884d1fb2234c74")}]
);
You may notice than instead of getting a first element of the array I specified which element of the sensors array I would like to update by providing its ObjectId.
Note that arrayFilters are passed as the third argument to the update query as an option.
You could now make "outer._id" dynamic by passing the ObjectId of the sensor like so: {"outer._id": req.body.sensorId}
In general, with the use of identifier, you can get to even deeper nested array elements by following the same procedure and adding more filters.
If there was a third level nesting you could then do something like:
User.findOneAndUpdate(
{ _id: "Manasa" },
{ $push: { "sensors.$[outer].measurements.$[inner].example": { "time": req.body.time } } }
{ "arrayFilters:" [{"outer._id": ObjectId("57da0a4bf3884d1fb2234c74"), {"inner._id": ObjectId("57da0a4bf3884d1fb2234c74"}}]
);
You can find more details here in the answer written by Neil Lunn.
refer ::: positional-all
--- conditions :: { other_conditions, 'array1.array2.field_to_be_checked': 'value' }
--- updateData ::: { $push : { 'array1.$[].array2.$[].array3' : 'value_to_be_pushed' } }

Date json Object json in angularjs

I have json result which contain set of json objects.I could not get json object because json object is in integer value.Here is my json result
[{
"serverdatetime": "2016-09-23 12:21:31",
"game_result_array": {
"2016-09-23": [{
"eShowOnHome": "Yes",
"dModifiedDate": "2016-09-22",
"eText": "No",
"eTodayGame": "No",
"eDelay": "No",
"eInvert": "None",
"eResultOrder": "No",
"iHGameID": "56444",
"iGameID": "120",
"vGameTitle": "Gana M\u00e1s",
"eStats": "Yes",
"vUrl": "gana-mas-loteria-nacional",
"vGameLogo": "https:\/\/s3.amazonaws.com\/cdn.kiskooloterias.com\/dominicanas\/upload\/game_logo\/120\/loteria-nacional-dominicana.jpg",
"companymodifieddate": "2011-12-19 13:35:54",
"vCompanyLogo": "https:\/\/s3.amazonaws.com\/cdn.kiskooloterias.com\/dominicanas\/upload\/company\/76\/1373805675_loteria-nacional.jpg",
"gamemodifieddate": "2016-01-05",
"iCompanyID": "76",
"vCompanyName": "Loter\u00eda Nacional",
"vCompanyurl": "loteria-nacional-resultados",
"dLastLotteryDate": "2016-09-22",
"tScore": "28 01 96"
}]
},
"company_ids": "75,76,77,78,84",
"game_ids": "93,94,95,96,98,127,92,111,120,131,100,101,102,114,117,108,171,172",
"success": "1",
"message": "Record found"
}]
Here is the code what i tried
$http({
url : baseUrl,
method :'Post',
data : param
})
.success(function (result) {
$scope.rank =result.game_result_array["2016-09-23"].eShowOnHome;
}
Is there anyway to get json objects? help me. Thanks in advance
game_result_array is an array, so you need to specify the index.
This should work fine.
$scope.rank =result.game_result_array["2016-09-23"][0].eShowOnHome;
You could cast variable that are meant to be integer, Because When Calling From The endpoint, the json with integer types will be shown as strings.
example below shows how you do that using laravel/lumen
$x = Data::all();
return (int)$x->price;
hope you get the idea

Elastic-search: How can i map json data having dynamic number of fields

I'm working on a application for that i need to map json data for storing in Elasticsearch. The number of fields in json data is dynamic.then how can i do mapping for this scenario.
mapping Snippet
var fs = uploadedFiles[0].fd;
var xlsxRows = require('xlsx-rows');
var rows = xlsxRows(fs);
console.log(rows);
client.indices.putMapping({
"index": "testindex",
"type": "testtype",
"body": {
"testtype": {
"properties": {
"Field 1": {
"type": "string"
},
"Field 3": {
"type": "string"
},
"Field 2":{
"type":"string"
} .....
//Don't know how many fields are in json object.
}
}
}
}, function (err, response) {
if(err){
console.log("error");
}
console.log("REAPONCE")
console.log(response);
});
This is my sample json data
//result of rows
[
{ Name: 'paranthn', Age: '43', Address: 'trichy' },
{ Name: 'Arthick', Age: '23', Address: 'trichy' },
{ Name: 'vel', Age: '24', Address: 'trichy' } //property fields
]
NOTE: The number of property fields are dynamic.
ES will always make its best efforts to infer the correct type for the fields in your documents that have no mapping defined and set sensible defaults.
A mapping is only necessary if you need to apply some special treatment to certain fields other than the set defaults, like specifying an indexing analyzer, a search analyzer, whether string fields need to be analyzed or not, specifying sub-fields with a different analyzer, etc.
If you don't need any of this, then you can let ES infer the mapping of your documents.

Search through list of objects in efficient way mongo

I have a json that looks a bit like this in meteor.
{
"_id": "someid",
"createdAt": ISODate("2015-03-10T14:26:02.430Z"),
"emails": [{
"address": "raven#corvid.com",
"verified": false
}, {
"address": "crow#corvid.com",
"verified": false
}]
}
I want to search the database and find if anyone has a given email, say, crow#corvid.com. If it were just a static value, you could do Meteor.users.findOne({ email: "crow#corvid.com" });, but the list makes it more complicated.
What is the efficient way to do this?
You can do this using $elemMatch operator to match the document that contains crow#corvid.com as address value.
Meteor.users.findOne({ emails: {$elemMatch: {address:"crow#corvid.com" }}})
you can also index the database, you can index embedded documents, your case an array Meteor.users.createIndex( { "emails" : 1 } )

How to access JSON element which has "-" character in the name in JavaScript

I have a JSON object which returns following values.
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}
}
I tried to access these results through JavaScript.
First I created an array and assigned these results to the array.
The content of the array (named articles) object looks like this;
abstract: "xxx"
authors: "yyy"
date: "1111"
keywords: "key1, key2"
paper-id: "abc"
paper-id-type: "xxx"
publication-forum: "yyy"
publication-forum-type: "zzz"
title: "www"
url: "url"
Then I tried to access each value in these elements using the format,
articles[0]["abstract"]
It works for elements that do not have "-" character. So when I tried to extract the paper-id;
articles[0]["paper-id"]
I'm getting the error [Exception: SyntaxError: Unexpected token []
Does anyone know how to solve this problem ?
The problem is because you forgot to close the [] and the {} in your JSON
You JSON should look like this
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}]
}
abc = {
"articles": [{
"paper-id": "id",
"paper-id-type": "type",
"title": "title",
"url": "url",
"abstract": "abs",
"date": "date",
"publication-forum": "forum",
"publication-forum-type": "type",
"authors": "auth",
"keywords": "key1,key2"
}
]
};
for (i in abc['articles'][0]) {
console.log(abc['articles'][0][i]);
}

Categories