Insert json string to mongoDB - json

I am new to Scala and MongoDB. I am writing a Scala program to read JSON string (it can be nested json string also) and insert the same to Mongo DB.
I tried below few things but its not working.
1) Tried to create an Document for the JSON string as below:
var document = (DBObject) JSON.parse(jsonString)
but getting the error
"value JSON is not member of object com.mongodb.DBObject".
2) Also tried with bson.Document as below but still can get it working
var myDoc = (Document.parse(schemajson))
Can anyone help me out on this? Please let me know if my approach is correct. If not the please do let me know what all things I need to do.
adding code:
val hadoopRDD = sc.textFile(data_file).foreach(line =>
{
data_array.clear
line.split("\t").foreach(word => data_array += word)
println(data_array)
var final_json = (schemajson.format(data_array: _*))
var document = (DBObject) JSON.parse(jsonString)
in above code final_json is the string having Json string like {"name": xyz, "age": 22}

I found the answer and below is the solution which worked for me.
I was simply using
var document = (DBObject) JSON.parse(jsonString)
which was causing error.
Instead we need to provide asInstanceOf[DBObject] which worked in my case
val dbObject: DBObject = JSON.parse(final_json_str).asInstanceOf[DBObject]

Related

JSON String parsing each character as an object

I have a JSON file that contains what I believe to be a correct JSON string:
{"title": "exampleTitle", "tipTitle": "exampleTipTitle", "tip": "exampleTip"}
I'm trying to parse said file and take out the 3 values then store them in variables, however currently, it parses each individual character as a separate object, therefore:
JSONobj[1] = "
and so on. Assuming that currentLocation = the directory location of the json file.
Code
var jsonLocation = currentLocation + "json.txt";
var request = new XMLHttpRequest();
request.open("GET", jsonLocation, false);
request.send(null);
var returnValue = request.responseText;
var JSONobj = JSON.parse(JSON.stringify(returnValue));
var headerTitle = JSONobj[0];
A few clarifications, the stringify is in because it was throwing an unexpected token error. I've tried changing the file tile to .json instead but that also makes no difference. "It also gives off a XMLHttpRequest on the main thread is deprecated" but I'm not particularly sure how to solve that issue. Any help would be appreciated.
var returnValue = request.responseText;
Here returnValue is a string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
var JSONobj = JSON.parse(JSON.stringify(returnValue));
Here you convert the string of JSON to JSON. So you have a JSON string representing a string, and that string is a representation of a data structure in JSON.
"\"{\\"title\\": \\"exampleTitle\\", \\"tipTitle\\": \\"exampleTipTitle\\", \\"tip\\": \\"exampleTip\\"}"
Then you parse it and convert it back to the original string of JSON.
"{\"title\": \"exampleTitle\", \"tipTitle\": \"exampleTipTitle\", \"tip\": \"exampleTip\"}
So you end up back where you start.
Just don't use JSON.stringify here, and you'll convert your JSON to a JavaScript object:
var javascript_object = JSON.parse(returnValue);
Then you have an object, but it doesn't have a 0 property so it doesn't make sense to access it with javascript_object[0]. The properties have names, such as javascript_object.title.
Your JSON doesn't describe an array, so indexing into it with an index like 0 doesn't make sense. Your JSON describes an object, which will have properties with the names title, tipTitle, and tip.
Additionally, you're overdoing your parsing: You just want to parse, not stringify (which is the opposite of parsing):
var JSONobj = JSON.parse(returnValue);
So:
var JSONobj = JSON.parse(returnValue);
var headerTitle = JSONobj.title;
console.log(headerTitle); // "exampleTitle"
Side note: By the time you've assigned it to the variable you've called JSONobj, it isn't JSON anymore, it's just a normal JavaScript object, so that name is a bit misleading. If you're writing source code, and you're not dealing with a string, you're not dealing with JSON anymore. :-)

deserialize json to general object (without predefined schema)

I'm trying to use json.net.
I'd like to get a string (in json format) and convert it to general json object, without predefined schema.
somelting like
var jsonString = #"{\""id\"": 1,\""name\"": \""A green door\""}";
var jsonMessage = JsonConvert.DeserializeObject<JObject>(jsonString);
var myValue = jsonMessage["name"]
Is that something doable? didn't make it work
Your string is malformed, try this string instead:
var jsonString = "{\"id\": 1,\"name\": \"A green door\"}";
You could also shorten this a little bit:
string name = JObject.Parse(jsonString)["name"].ToObject<string>();

Parse json string that carries a collection of objects in actionscript using Json.parse

I am running into an error parsing a json string with JSON.parse(...)
var str:String= '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Object = JSON.parse(str);
I can tell that I am getting the syntax wrong with constructing the JSON string but I have tried quite a few things before giving up. Any help with how to deal with collections would be great.
The following simple case works for me
var str:String= '{"test":"line1"}';
var propertySets:Object = JSON.parse(str);
Thank you
The syntax in the JSON string is correct. The way it is formatted will return an Array instance from JSON.parse(). The following code works for me:
var str:String = '[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3", "BB":"14"}]';
var propertySets:Array = JSON.parse(str) as Array;
trace(propertySets[0].AA); // prints "A1"
trace(propertySets[0].BB); // prints "32"
Shot in the dark since I don't know actionscript, but try wrapping the array in an object
var str:String= '{"objectArray":[{"AA":"A1", "BB":"32"}, {"AA":"A2", "BB":"12"}, {"AA":"A3","BB":"14"}]}';

Play 2.1 Reading JSON Objects in order

JSON to Parse: http://www.dota2.com/jsfeed/heropickerdata?v=18874723138974056&l=english
Hero Class and JSON Serialization
case class Hero(
var id:Option[Int],
name: String,
bio: String,
var trueName:Option[String]
){}
implicit val modelReader: Reads[Hero] = Json.reads[Hero]
Reading Data
val future: Future[play.api.libs.ws.Response] = WS.url("http://www.dota2.com/jsfeed/heropickerdata?v=18874723138974056&l=english").get()
val json = Json.parse(Await.result(future,5 seconds).body).as[Map[String, Hero]]
var i = 1
json.foreach(p => {
p._2.trueName = Some(p._1)
p._2.id = Some(i)
p._2.commitToDatabase
i += 1
})
I need to get the id of each hero. The order of heros in the json matches their id. Obviously a map is unordered and wont work. Does anyone have any other ideas?
I have tried to use a LinkedHashMap. I even tried to make an implicit Reads for LinkedHashMap but I've failed. If anyone thinks that this is the answer then would you please give me some guidance?
It keeps just saying "No Json deserializer found for type scala.collection.mutable.LinkedHashMap[String,models.Hero]. Try to implement an implicit Reads or Format for this type.". I have the trait imported into the file i'm trying to read from. I have a funny feeling that the last line in my Reads is the problem. i think I can't just do the asInstanceOf, however I have no other ideas of how to do this reads.
LinkedHashMap Implicit Reads Code: http://pastebin.com/cf5NpSCX
You can try extracting data in order from the JsObject returned by Json.parse directly, possibly like this:
val json = Json.parse(Await.result(future,5 seconds).body)
val heroes: Map[String, Hero] = json match {
case obj: JsObject =>
obj.fields.zipWithIndex.map{ case ((name: String, heroJson: JsValue), id) =>
heroJson.asOpt[Hero].map{ _.copy(id = Some(id)) }
}.flatten.toMap
case _ = > Seq.empty
}
I don't believe you'll need an order-preserving map anymore since the ids are generated and fixed.

Trouble parsing JSON in ActionScript 3 -- "Unexpected c encountered"

I am trying to parse a JSON file in ActionScript 3.
So far I imported this...
import com.adobe.serialization.json.JSON;
I have created the JSON class:
[Embed(source="myfile.json",mimeType="application/octet-stream")]
private var json_file:Class;
And then I try to parse the JSON
var jsonObj:Object = JSON.decode(json_file);
When I run the JSON.decode line, I get this error:
JSONParseError: Unexpected c encountered
I have tried to find out what I am doing wrong, but Google Search didn't seem to help. I have tried different and basic JSON files to ensure it isn't my file.
json_file is a Class, rather than an instance. You should just need to pass a new instance of json_file to the decoder:
var jsonObj:Object = JSON.decode(new json_file());
It turns out I read the API wrong. The decode function needs a string, not a class. Here was my solution:
var bytes:ByteArray = new json_file();
var json:String = bytes.readUTFBytes(bytes.length);
var jsonObj:Object = JSON.decode(json);