I am querying a Mongo DB in Scala and looping through the returned elements, that look like this:
{ "_id" : "123:1350918540586068000:v" ,
"i" : {
"vendorStyle" : "coolStyle" ,
"createdAt" : 1350918540580 ,
"productId" : "product123" ,
"skuId" : "123"
}
}
My question is: how do I retrieve the value from skuId? I know you can use the notation parent.child in the 'find' method in Mongo, but that doesn't work when reading from the resulting DBObject
This is the code:
val elems = SkuStorage.collection.find(MongoDBObject("i.productId" -> productId))
elems.toSeq.map { element=>
readSkuById(element.get("i.skuId")) //breaks!
}
Do I need to go get("i") then parse the string into a JSON? Is there any better way of handling this?
You could try
element.expand[String]("i.skuId")
it returns Option[String]
Related
So I have Json obj which I convert via JSON.stringfy and the result is:
{
"data" : [ {
"id" : 417206355511802,
"name" : "test01"
}, {
"id" : 421211003974634,
"name" : "test02"
}, {
"id" : 403713622404901,
"name" : "test03"
}]
}
How can I access each name value? I was trying:
var test = result[0].name;
alert(test);
You can't access anything from the result of stringify() - it produces a string, hence its name. Rather, it sounds like you started with a string and converted it to an object via JSON.parse().
If that's not the case, and you already have the object, you don't need to stringify if you want to access properties.
That out of the way, you're missing the data step.
myobj.data[0].name; //<-- where myobj is the variable holding the object
JSON.stringify will not help you.becouse it's give a string as output.you can directly access the object elements by
var arr = myObj.data;
arr.forEach(function(elem) {
console.log(elem.id);
console.log(elem.name);
});
I am trying to pass this json string to my other method but SOMETIMES I get this error,
play.api.libs.json.JsResultException:
JsResultException(errors:List((,List(ValidationError(error.expected.jsstring,WrappedArray())))))
I find it strange that this occurs randomly, sometimes I don't get the exception and sometimes I do. Any ideas?
Here is what my json looks like
val string = {
"first_name" : {
"type" : "String",
"value" : "John"
},
"id" : {
"type" : "String",
"value" : "123456789"
},
"last_name" : {
"type" : "String",
"value" : "Smith"
}
}
I read it like
(string \ "first_name").as[String]
(string \ "first_name") gives JsValue not JsString so as[String] does not work.
But if you need first name value you can do
val firstName = ((json \ "first_name") \ "value").as[String]
This is another option to consider for type safety while reading and writing Json with play Json API. Below I am showing using your json as example reading part and writing is analogous.
Represent data as case classes.
case Person(id:Map[String,String], firstName:Map[String,String], lastName:[String,String]
Write implicit read/write for your case classes.
implicit val PersonReads: Reads[Person]
Employ plays combinator read API's. Import the implicit where u read the json and you get back the Person object. Below is the illustration.
val personObj = Json.fromJson[Person](json)
Please have a look here https://www.playframework.com/documentation/2.6.x/ScalaJsonAutomated
First of all you can't traverse a String object, so your input must be converted to JsValue to be able to traverse it:
val json = Json.parse(string)
then the first_name attribut is of JsValue type and not a String so if you try to extract the first_name value like you do you will get always a JsResultException.
I can only explain the random appearance of JsResultException by a radom change in your first_name field json structure. make sur your sting input to traverse has always a fixed first_name filed structure.
My fetched DBObject looks like following
{ "_id" : { "$oid" : "50c28ac1de86acf0bdfbeca0"} ,
"schedule" : { "startAt" : 1354926785198 , "endAt" : 1391155200000 , "repeatForever" : true , "interval" : 3600} , "destination" : "Storage-East"}
I want to extract JSON string sans "_id" so that I can deserialize it back to my Java object. If I use following I can remove the '_id' field and it is fine to get the Java object back from JSON String. Is there any other elegant way of doing this ?
dbObj.removeField("_id");
String jsonString = dbObj.toString();
// Now readValue from the json string
thanks.
Instead of removing the data afterwords, just use results projections. You simply remove the _id by using the result projections in a find statement:
//find all documents where destination equals Storage-East, but exclude _id from result set
db.inventory.find( { "destination": 'Storage-East' }, { _id:0 } )
You can find the documentation http://docs.mongodb.org/manual/core/read-operations/#result-projections.
Im pretty new to JavaScript and Mongoose. I ended with a bit weird designed JSON which I want to persist via mongoose.
This is an example of this JSON:
{name : "a_string", a1 : {something : 'a_number', something_else : 'a_number'}, a2 : {...} }
a1, a2 are variable (not always there are a1 neither a2, maybe there are others)
something, something_else are variable also, can be different identifiers -they are properties-.
Maybe its my fault designing such a weird JSON but what would be the best way of defining a Schema for it?
I have various alternatives, neither convince me:
Schema {
myJSON : []
}
This is very ugly but now i could store my JSON as myJSON[0] = {name: "theName"...}. Ofc is the ugliest, but the most close I have found to my original data-structure.
another one
json Schema {
name: String,
parts: [part]
}
part Schema {
name : String,
props : [prop]
}
prop Schema {
name : String,
value : Numeric
}
This is more pretty BUT then I find several troubles, the final JSON will have many arrays and indirections I didnt have on the original one:
{name :"a_string", parts:[{name : "a1",
props : [{name : "something", value: 'a_number'}]},{...}]}
is there any way of removing all these annoying arrays from the Schema¿?
UPDATE:
Finally I have solved my issue because I could adapt my datamodel a bit:
var mySchema = new Schema({
name : String
, valid : Boolean
, parts : {}
});
Then the "props" contains all the JSON I want (except name is put outside). This is not the way I had in mind but it works fine (I think).
It looks like you are using mongoose embedded documents.
I'm not sure if embedded documents will always be wrapped inside arrays.
Following this mongoose documentation example :
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
A BlogPost can contains severals Comments, and Comments will be wrapped inside an array (just like your issue if i'm right).
What if you get rid of that array in the schema definition ?
Using Comments instead of [Comments] :
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : Comments
, meta : {
votes : Number
, favs : Number
}
});
I can't try that now.
Otherwise, I have an idea using mongoose virtual attributes, if this doesn't work, let me know.
Edit
Using virtual attributes, you could do something like this :
BlogPost
.virtual('customComment')
.get(function() {
return this.comments[0];
});
This will return the first Comment entry object whithout the array.
var BlogPost = mongoose.model('BlogPost');
BlogPost
.find({ title: 'foo' })
.populate('comments')
.run(function (err, post) {
console.log(post.customComment); // returns the first comment without array
});
Not tested, this may contains typos.
I have this JSON format:
string jsonFormat = #"{
""Applications"": {
""data"": {
""Application named one"": [
{
""index"" : ""1"",
""name"" : ""One"",
""active"" : ""1"",
""excluded"" : ""false""
}
],
""Application named two"": [
{
""index"" : ""2"",
""forum"" : ""yes"",
}
]
}
}
}";
How exactly I can acces data childrens ? I need to retreive Application named one and Application named two - for each also the attributes with their values - the attributes are different from Application to Application.
Untill now I have:
JObject resultt= JObject.Parse(jsonFormat);
// get JSON result objects into a list
IList<JToken> results = resultt["Applications"]["data"].Children().ToList();
I looked over JSON.net documentation and could not find a solution for this...
Any help will be very usefull. Thank you.
I think you are looking for something like this:
JObject jObject = JObject.Parse(jsonFormat);
int index = jObject
.Value<JObject>("Applications")
.Value<JObject>("data")
.Value<JArray>("Application named one")
.First
.Value<int>("index");
Basically the idea is to use the Value method with the type you are expecting to retrieve a specific json element (JObject, JArray, ...) or parse a .NET value (int, string, bool, ...).