I need to pull the value of property "title"
KV = {
clientPath: '/0000000000/client',
serverPath: '',
application: '/00000000/client/application/player.js',
properties: '/000000000/client/custom-config/AppProperties.js',
pollingEnabled: false,
customerConfig: {},
presentationTypeConfig: {},
kuluConfig: {},
kulu: {
"guid" : "XXXXXXX",
"title" : "XXXXX",
"createdInApp" : false,
"allowFeedback" : true,
"publisher" : {
"id" : 000000001,
"username" : "XXXXXXX",
"name" : "XXXXXXXX"
},
I tried looping but I just get returned undefined.
I have no access to the code to change it.
Have you tried this?
KV.kulu.title
first of all: the json you have posted is invalid. publisher-property has only an opening curly bracket.
second: here's a working fiddle, with valid json and just the code kv.kulu.title which does exactly what you are (literally) asking for:
http://jsfiddle.net/k75cxdkh/1/
edit: I'm just guessing here, but re-reading your question and json code, it seems you try to loop over an array of objects to get a nested object by it's value dynamically. When trying this, do it e.g. like this (using underscorejs):
var arr = _.filter(KV, function(obj) {
return _.some(obj.kulu, {id: ID_TO_FIND});
});
if not, nevermind. It's just a bit weird you are asking for a such common task.
quick and easy: KV.kulu.title no loop required!
Related
I am trying to update a document in Mongo if it has a certain value within a field.
{
"_id" : ObjectId("myObject"),
"source" : "BW",
"sourceTableName" : "myTable",
"tableName" : "tier",
"type" : "main",
"fieldMappings" : [
{
"sourceField" : "tier_id", <~~~~ If this is "tier_id", I want to change it to "trmls_id"
"reportingField" : "bw_id",
"type" : "integer",
"defaultMap" : {
"shouldErrorOnConvert" : false
}
}
]
}
I tried something like
db.getCollection('entityMap').update({"sourceTableName":"myTable"}, {"fieldMappings.0.sourceField":"trmls_id":{$exists : true}}, { $set: { "fieldMappings.0.sourceField": "tier_id" } })
and I think it is failing on the $exists parameter I am setting.
Is there a more cleaner/dynamic way to do this?
The whole query I am trying to formulate is
In the table myTable
I want to check if there is a sourceField that has the value tier_id
If there is tier_id, then change it to trmls_id
Otherwise do nothing
If there is a similar StackOverflow question that answers this, I am happy to explore it! Thanks!
There is a syntax mistake and you can use positional operator $ in update part because you have already selector field in query part,
db.getCollection('entityMap').update(
{
"sourceTableName": "myTable",
"fieldMappings.sourceField": "tier_id" // if this field found then it will go to update part
},
{
$set: {
"fieldMappings.$.sourceField": "trmls_id"
}
}
)
I have a JSON object like so, (this is an example)
house.keys = {
"key1" : "23456",
"key2" : "97543",
"key3" : "35493"
}
house.doors = [{
"name" : "Front door",
"lock key" : house.keys.key1
}, {
"name" : "Back door",
"lock key" : house.keys.key2
}
]
This object is stored in the DB as a string, and read and parsed() on page load. It will likely be edited by user interaction, then the altered object needs to be stringify()-ed and written back into DB. I've got everything working except for a problem in the stringify() function.
Instead of this:
"lock key" : house.keys.key1
I get this:
"lock key" : "23456"
How do I get the stringify() method to return the referenced object's name instead of the referenced object, itself.
I've looked into using a replacer function:
JSON.stringify(house, replacer); // Where replacer() returns 'something else' for "lock key", but I don't know what 'something else' is.
Thanks.
Just enclose the name in quotes so that it will be treated as a string and therefore, the value will not be parsed and put.
house.doors = [{
"name": "Front door",
"lock key": "house.keys.key1"
}, {
"name": "Back door",
"lock key": "house.keys.key2"
}]
This does appear to be the best solution to my problem. It did require a change to the code that was using the 'house' object.
Before, I was referencing the key as such:
var key1 = house.doors[0]["lock key"];
Now I have to use:
var key1 = house.doors[0]["lock key"];
var key1 = eval(key1);
(I believe I've written this right. My actual code is considerably different.)
All in all, an easier fix then the other solutions I was contemplating.
i have data that looks like this in my database
> db.whocs_up.find()
{ "_id" : ObjectId("52ce212cb17120063b9e3869"), "project" : "asnclkdacd", "users" : [ ] }
and i tried to add to the 'users' array like thus:
> db.whocs_up.update({'users.user': 'usex', 'project' : 'asnclkdacd' },{ '$addToSet': { 'users': {'user':'userx', 'lastactivity' :2387843543}}},true)
but i get the following error:
Cannot apply $addToSet modifier to non-array
same thing happens with push operator, what im i doing wrong?
im on 2.4.8
i tried to follow this example from here:
MongoDB - Update objects in a document's array (nested updating)
db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} ,
{$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
false ,
true)
the python tag is because i was working with python when i ran into this, but it does nto work on the mongo shell as you can see
EDIT ============================== GOT IT TO WORK
apparently if i modify the update from
db.whocs_up.update({'users.user': 'usex', 'project' : 'asnclkdacd' },{ '$addToSet': { 'users': {'user':'userx', 'lastactivity' :2387843543}}},true)
to this:
db.whocs_up.update({'project' : 'asnclkdacd' },{ '$addToSet': { 'users': {'user':'userx', 'lastactivity' :2387843543}}},true)
it works, but can anyone explain why the two do not achieve the same thing, in my understanding they should have referenced the same document and hence done the same thing,
What does the addition of 'users.user': 'userx' change in the update? does it refer to some inner document in the array rather than the document as a whole?
This is a known bug in MongoDB (SERVER-3946). Currently, an update with $push/$addToSet with a query on the same field does not work as expected.
In the general case, there are a couple of workarounds:
Restructure your update operation to not have to query on a field that is also to be updated using $push/$addToSet (as you have done above).
Use the $all operator in the query, supplying a single-value array containing the lookup value. e.g. instead of this:
db.foo.update({ x : "a" }, { $addToSet : { x : "b" } }, true)
do this:
db.foo.update({ x : { $all : ["a"] } }, { $addToSet : { x : "b" } } , true)
In your specific case, I think you need to re-evaluate the operation you're trying to do. The update operation you have above will add a new array entry for each unique (user, lastactivity) pair, which is probably not what you want. I assume you want a unique entry for each user.
Consider changing your schema so that you have one document per user:
{
_id : "userx",
project : "myproj",
lastactivity : 123,
...
}
The update operation then becomes something like:
db.users.update({ _id : "userx" }, { $set : { lastactivity : 456 } })
All users in a given project may still be looked up efficiently by adding a secondary index on project.
This schema also avoids the unbounded document growth of the above schema, which is better for performance.
I made this object literal and I don't understand what is the right brackets positioning for the array that comes after active. Why am I getting missing brackets error?
var players = {
player1 : {
active : true,
[
{
row : 1,
square : 1
},{
row : 2,
square : 1
},{
row : 3,
square : 1
}
]
}
};
The value of the active property can be either the boolean true or an array. It can't be both.
You need to change it to either:
active : [ ... ]
or
active : true,
somethingElse : [ ... ]
or some other valid data structure.
First off, that's not JSON, that's a JavaScript object initializer (sometimes called an "object literal").
The problem is the [ here:
active: true,
[
You need a key before that value. The basic form is key: value, where the key is the name of the property (can be an identifier, a number, or a string in JavaScript; in JSON it would have to be a string, and in double quotes not single quotes) and the value is, well, the value. :-)
active is set to 2 values, true and your array. To test your JSON, use http://jsonlint.com/.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON pretty print using JavaScript
I'm working on a project that will be used to help analyse and understand JSON arrays by future developers of a platform. I'm referencing Facebook's brilliant Graph Explorer page, seen here, and want to output our array in a prettified, correctly tab indented and line breaker array, just as it does on the explorer.
The arrays are outputted to a textarea, and because of this I think I'm running into issues with the line breaking and tabbing. I've also tried using the prettify library, but with no luck.
Example:
{"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null}
To:
{
"outcome":"success",
"result":{
"name":"messaging-sockets",
"default-interface":"external",
"include":[
],
"socket-binding":{
"messaging":{
"name":"messaging",
"interface":null,
"port":5445,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
},
"messaging-throughput":{
"name":"messaging-throughput",
"interface":null,
"port":5455,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
}
}
},
"compensating-operation":null
}
You may use JSON.stringify:
JSON.stringify(jsonobj,null,'\t')
See the demo.
UPDATE: If you don't have jsonobj,but have json string,then before using stringify function,convert json string to json object by this line:
jsonobj = JSON.parse(jsonstring);