How to parse json object in UnityScript? - unity3d

I am following this link http://wiki.unity3d.com/index.php/JSONUtils but not able to parse json object.
What I have tried so far:
function SerializeObject()
{
var object = {"response":[{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"},{"id":"99","name":"Guest","score":"18","game":"7,8,2,5,6,9,4,3","date":"2015-02-28 11:19:35"},{"id":"89","name":"Guest","score":"17","game":"5,7,2,8,6,1,3,9","date":"2015-02-26 16:39:59"},{"id":"96","name":"Guest","score":"18","game":"2,6,1,5,9,7,8,4","date":"2015-02-26 16:34:05"},{"id":"97","name":"Guest","score":"16","game":"1,7,3,4,8,2,6,5","date":"2015-02-26 16:32:30"},{"id":"95","name":"Guest","score":"14","game":"1,3,7,4,6,9,2,8","date":"2015-02-23 19:20:07"},{"id":"90","name":"Guest","score":"16","game":"8,3,9,6,4,5,2,7","date":"2015-02-23 16:48:55"},{"id":"92","name":"Guest","score":"17","game":"5,2,1,9,7,4,3,8","date":"2015-02-23 16:48:28"},{"id":"91","name":"Guest","score":"16","game":"2,1,3,9,6,7,8,4","date":"2015-02-23 16:48:06"},{"id":"94","name":"Guest","score":"14","game":"5,2,8,7,6,1,9,4","date":"2015-02-23 16:47:25"},{"id":"93","name":"Guest","score":"16","game":"8,9,2,7,4,6,3,1","date":"2015-02-23 16:45:44"},{"id":"88","name":"jacky chain","score":"15","game":"1,2,5,4,7,9,3,6","date":"2015-02-23 13:35:20"},{"id":"87","name":"Genie","score":"15","game":"8,9,5,7,1,4,2,3","date":"2015-02-22 16:19:32"},{"id":"86","name":"Genie","score":"15","game":"9,7,3,2,1,5,8,4","date":"2015-02-22 16:16:13"},{"id":"85","name":"Genie","score":"15","game":"7,1,4,6,5,3,9,8","date":"2015-02-22 14:25:39"},{"id":"83","name":"new","score":"18","game":"2,5,4,1,8,9,7,6","date":"2015-02-22 11:11:49"},{"id":"84","name":"Guest","score":"15","game":"9,8,3,5,1,4,2,7","date":"2015-02-22 09:48:28"},{"id":"80","name":"Guest","score":"16","game":"5,4,2,3,1,8,7,6","date":"2015-02-22 08:24:55"},{"id":"82","name":"Guestr","score":"15","game":"8,1,9,5,7,4,6,3","date":"2015-02-21 21:00:37"},{"id":"81","name":"Guest","score":"18","game":"9,4,2,7,6,5,1,8","date":"2015-02-21 20:54:51"},{"id":"79","name":"Guest","score":"15","game":"2,6,9,5,8,3,1,7","date":"2015-02-21 20:37:30"},{"id":"78","name":"Guest","score":"15","game":"3,6,9,7,1,5,4,2","date":"2015-02-21 20:35:27"},{"id":"77","name":"Guest","score":"17","game":"5,3,7,9,8,4,1,6","date":"2015-02-21 16:04:17"},{"id":"64","name":"Guest","score":"17","game":"7,9,8,4,6,1,3,5","date":"2015-02-21 16:03:41"},{"id":"76","name":"new","score":"18","game":"9,3,4,8,6,5,2,1","date":"2015-02-21 15:27:25"}]};
for( var test in object.Keys )
{
Debug.Log( "Object["+test+"] : "+object[test] );
}
}
I see the below line in the Log:
Object[response] : Boo.Lang.Hash[]
Now i want to extract value from this object.
I would appreciate your help on this, thank you.

Your log message is telling you that object["response"] is returning an array of hashes as you would expect from the JSON you parsed. Now you need to iterate over that array which will give you each internal hash object, the first one being:
{"id":"100","name":"Guest","score":"14","game":"3,6,9,7,1,8,2,4","date":"2015-02-28 11:22:32"}

Related

What am I doing wrong with this Python class? AttributeError: 'NoneType' object has no attribute 'usernames'

Hey there I am trying to make my first class my code is as follows:
class Twitt:
def __init__(self):
self.usernames = []
self.names = []
self.tweet = []
self.imageurl = []
def twitter_lookup(self, coordinents, radius):
twitter = Twitter(auth=auth)
coordinents = coordinents + "," + radius
print coordinents
query = twitter.search.tweets(q="", geocode='33.520661,-86.80249,50mi', rpp=10)
print query
for result in query["statuses"]:
self.usernames.append(result["user"]["screen_name"])
self.names.append(result['user']["name"])
self.tweet.append(h.unescape(result["text"]))
self.imageurl.append(result['user']["profile_image_url_https"])
What I am trying to be able to do is then use my class like so:
test = Twitt()
hello = test.twitter_lookup("38.5815720,-121.4944000","1m")
print hello.usernames
This does not work and I keep getting: "AttributeError: 'NoneType' object has no attribute 'usernames'"
Maybe I just misunderstood the tutorial or am trying to use this wrong. Any help would be appreciated thanks.
I see the error is test.twitter_lookup("38.5815720,-121.4944000","1m") return nothing. If you want the usernames, you need to do
test = Twitt()
test.twitter_lookup("38.5815720,-121.4944000","1m")
test.usernames
Your function twitter_lookup is modifying the Twitt object in-place. You didn't make it return any kind of value, so when you call hello = test.twitter_lookup(), there's no return value to assign to hello, and it ends up as None. Try test.usernames instead.
Alternatively, have the twitter_lookup function put its results in some new object (perhaps a dictionary?) and return it. This is probably the more sensible solution.
Also, the function accepts a coordinents (it's 'coordinates') argument, but then throws it away and uses a hard-coded value instead.

Meteor.js : How to run check() when arguments are Mongodb ObjectId's?

In some of my Meteor methods, I'm sending Mongodb ObjectId's from the client as arguments. I'd like to run these through Meteor's check() system but I can't seem to find anything that matches successfully with them.
I've tried
var someObjectId = Meteor.Collection.ObjectId();
check(someObjectId, Meteor.Collection.ObjectId()) // fails
check(someObjectId, { _str : String }) //fails
check(someObjectId, String) //fails
any help much appreciated !
Instead of:
check(someObjectId, Meteor.Collection.ObjectID());
Try without the parentheses:
check(someObjectId, Meteor.Collection.ObjectID);
Edit-
Note that the error message for this check isn't ideal.
check({}, Meteor.Collection.ObjectID);
// Error: Match error: Expected
You could assume the message should be something like
// Error: Match error: Expected ObjectId, got object
You can see why this happens in this snippet from the check package.
https://github.com/meteor/meteor/blob/devel/packages/check/match.js
if (pattern instanceof Function) {
if (value instanceof pattern)
return;
// XXX what if .name isn't defined
throw new Match.Error("Expected " + pattern.name);
}
Meteor.Collection.ObjectID does not have name property.
As an alternative solution, you could simply pass the hexadecimal string as an argument instead of the ObjectID.
var idValidator = Match.Where(function (id) {
check(id, String);
return /[0-9a-fA-F]{24}/.test(id);
});
check(new Meteor.Collection.ObjectID()._str, idValidator);
// success
check('', idValidator);
// Error: Match error: Failed Match.Where validation
check({}, idValidator);
// Error: Match error: Expected string, got object
check([], idValidator);
// Error: Match error: Expected string, got object <--- bug? I expect array
Note, this regular expression is pulled from here.
https://github.com/mongodb/js-bson/blob/master/lib/bson/objectid.js
You should use following to generate a random ObjectID:
var someObjectId = new Meteor.Collection.ObjectID();
As Cuberto said, you can then check it by Meteor.Collection.ObjectID:
check(someObjectId, Meteor.Collection.ObjectID)
Normally when using check() you're not in a position to generate a new Meteor _id. Here's an alternative using Match.check()
First extend the Match object with:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
This is useful because you're likely to be checking _ids in many of your methods.
Now simply:
check(_id,Match._id);
more on this pattern
Complete answer to the original question:
First, define a matcher for a single object in your array of arguments:
Match._id = Match.Where(function (id) {
check(id, String);
return /[a-zA-Z0-9]{17,17}/.test(id);
});
Then you can call:
check(MyArrayOfArguments, [Match._id])

how to parse SMValue to String array

I am just getting familiar with the StackMob server side custom code sdk and i am trying to get a relationship field and iterate through it in the form of a String array. How do i do that ? is it possble to iterate through it without parsing it into an array?
DataService ds = serviceProvider.getDataService();
List<SMCondition> query = new ArrayList<SMCondition>();
query.add(new SMEquals("product_id", new SMString(jsonObj.getString("product_id"))));
List<SMObject> results = ds.readObjects("product", query);
SMObject product= results.get(0);
//product.getValue().get("categories"); how do i get this to be a String array?
At its simplest, that would look something like this:
List<SMValue> categories = (List<SMValue>)(rawObj.getValue().get("categories").getValue());
for (SMValue smString : categories) {
SMString stringValue = (SMString)smString.getValue();
//do whatever you want with the string value here
}
Obviously there are some unchecked casts in here, so you will want to add type/null checking to the appropriate sections depending on your data & schema.

error .match expression results null

I am working on a mail merge script. I have used Logger.log to find out that the error is in the expression that tells match what to find. In my case I am trying to pull all the keys that are inside ${xxxxxxx}. Below is what I have and I need help cleaning it up because at this point it returns null.
var template = "This is an example ${key1} that should pull ${key2} both keys from this text."
var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);
Thanks for any guidance anyone can share on this problem.
-Sean
I am not really familiarized with Google Apps Script, but I think this code in Javascript can help you.
It looks for all the ocurences of ${key} and returns each value inside the ${ }. I think that is what you are looking for.
var template = "This is an example ${key1} that should pull ${key2} both keys from this text.";
var matches = template.match(/\$\{[0-9a-zA-Z]*\}/mg);
console.log(matches);
for ( var i = 0; i < matches.length; i++ ) {
console.log(matches[i].replace(/[\$\{|\}]/gm, ""));
}

Passing query results in a viewbag

This seems like it should be so easy, but I've tried three or four ways to do it (but to no avail).
I'm just trying to put a query result in a viewbag and display it.
I've tried putting a model object list in a ViewBag:
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG;
ViewBag.messages = MSG;
And then I try to spit it out in a .cshtml:
var message = (List<LemonTrader.Models.Message>)ViewBag.messages; // <--- fails here because it is a string
foreach ( var MSG in message )
{
#Html.Label(MSG.msg)<br />
}
But it says:
Cannot convert type
'System.Data.Entity.Infrastructure.DbQuery'
to
'System.Collections.Generic.List'
So it seems I'm using using the wrong template. How do I spit out a System.Entity.Infrastructure.DbQuery?
I've also tried passing the results through the Viewbag as a list of strings. (Is that a worse way to do it?)
var mesg = from MSG in lemondb.Messages
where MSG.msg == Membership.GetUser().ToString()
select MSG.msg;
ViewBag.messages = mesg;
And spitting it out as a string list:
foreach (var atext in ViewBag.messages as List<string>) { // gets hung up on foreach here (why???)
#Html.Label( atext )
}
And I get this:
Object reference not set to an
instance of an object.
And it points at the "foreach" keyword.
Does that mean there were no messages? Or what?
I wish there was a tutorial showing how to put queryresults in a ViewBag and how to get them out! I've seen tutorials that return an object.ToList() without respect to any kind of "where" mechanism, but no examples to pull out a few, relevant entries and display them.
Try
ViewBag.messages = MSG.ToList();
Also, System.Data.Entity.Infrastructure.DbQuery implements IEnumerable ( http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbquery(v=vs.103).aspx ) so this should also work:
var message = (IEnumerable<LemonTrader.Models.Message>)ViewBag.messages;