Extracting complete JSON object from mongo db object - json

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.

Related

EvaluateJsonPath unable to return a scalar

I'm trying to extract a value from JSON to a flowfile-attribute. When I run the EvaluateJsonPath processor I get an error stating
"Unable to get a scalar value for expression $..fields.storyBoard.stringValue.
Input JSON looks like this:
{
"name" : "projects/fakedims-0000/databases/(default)/documents/device/0000",
"fields" : {
"reportKey" : {
"stringValue" : "abc123"
},
"dateOccured" : {
"timestampValue" : "2018-10-14T04:00:00Z"
},
"storyBoard" : {
"stringValue" : "https://path/to/media"
},
"new" : {
"integerValue" : "25"
},
"name" : {
"stringValue" : "device one"
},
"location" : {
"geoPointValue" : {
"latitude" : -78.413751,
"longitude" : 38.156487
}
}
},
"createTime" : "2018-10-19T00:02:26.209335Z",
"updateTime" : "2018-10-19T22:22:24.382136Z"
}
The JSONPath expression is $..fields.storyBoard.stringValue
What I think is happening is that the processor is returning ["https://path/to/media"] rather than just the string.
This is what I get if a evaluate to flowfile-content rather than an attribute. Why? What can I do to fix it?
Change the Return Type property value to json in EvaluateJsonPath processor, if you are extracting as flowfile-attribute
Return Type property description:
Indicates the desired return type of the JSON Path expressions.
Selecting 'auto-detect' will set the return type to 'json' for a
Destination of 'flowfile-content', and 'scalar' for a Destination of
'flowfile-attribute'.
As you are trying to extract nested key not the key on the root level(ex:name,createTime..), that's the reason why we need to configure the Return Type as Json not as scalar.
In Addition you can use FlattenJson processor(seperator '_') to flatten-out all nested json then use Return Type as auto detect in EvaluateJsonPath processor.
EvaluateJsonConfigs:
Output:
We are going to have attribute value without enclosing in an array

JSON.stringify - accessing data

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);
});

Scala Play Json JSResultException Validation Error

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.

Retrieving nested element from MongoCursor

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]

Deserialize JSON using JSON.net in Wp7 application

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, ...).