Twitter search api entities with media not working with Json.net for Windows phone Mango silverlight - silverlight

Below is my returned json from twitter
{
"created_at": "Sat, 11 Feb 2012 06:38:28 +0000",
"entities": {
"hashtags": [
{
"text": "Shubhdin",
"indices": [
9,
18
]
}
],
"urls": [],
"user_mentions": [
{
"screen_name": "SAMdLaw",
"name": "Sabyasachi Mohapatra",
"id": 104420398,
"id_str": "104420398",
"indices": [
0,
8
]
}
]
},
"from_user": "nilayshah80",
"from_user_id": 213599118,
"from_user_id_str": "213599118",
"from_user_name": "Nilay Shah",
"geo": {
"coordinates": [
18.6003,
73.825
],
"type": "Point"
},
"id": 168222351106899968,
"id_str": "168222351106899968",
"iso_language_code": "in",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1528184590/IMG_0465_normal.JPG",
"source": "<a href="http://twabbit.wordpress.com/" rel="nofollow">twabbit</a>",
"text": "#SAMdLaw #Shubhdin mitra",
"to_user": "SAMdLaw",
"to_user_id": 104420398,
"to_user_id_str": "104420398",
"to_user_name": "Sabyasachi Mohapatra",
"in_reply_to_status_id": 168219865197461505,
"in_reply_to_status_id_str": "168219865197461505"
},
{
"created_at": "Sun, 12 Feb 2012 01:54:07 +0000",
"entities": {
"hashtags": [
{
"text": "IWIllAlwaysLoveYou",
"indices": [
88,
107
]
}
],
"urls": [],
"user_mentions": [],
"media": [
{
"id": 168513175187238912,
"id_str": "168513175187238912",
"indices": [
108,
128
],
"media_url": "http://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"media_url_https": "https://p.twimg.com/Alat1wsCMAAh-wE.jpg",
"url": "http://shortener.twitter.com/dRc4dXH3",
"display_url": "pic.twitter.com/dRc4dXH3",
"expanded_url": "http://twitter.com/RIPWhitneyH/status/168513175183044608/photo/1",
"type": "photo",
"sizes": {
"orig": {
"w": 395,
"h": 594,
"resize": "fit"
},
"large": {
"w": 395,
"h": 594,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 340,
"h": 511,
"resize": "fit"
},
"medium": {
"w": 395,
"h": 594,
"resize": "fit"
}
}
}
]
},
"from_user": "RIPWhitneyH",
"from_user_id": 19319043,
"from_user_id_str": "19319043",
"from_user_name": "RIP Whitney Houston",
"geo": null,
"id": 168513175183044608,
"id_str": "168513175183044608",
"iso_language_code": "en",
"metadata": {
"recent_retweets": 8,
"result_type": "popular"
},
"profile_image_url": "http://a2.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"profile_image_url_https": "https://si0.twimg.com/profile_images/1820957590/images__13__normal.jpg",
"source": "<a href="http://twitter.com/">web</a>",
"text": "R-T if you think that the Grammy's should organize an \"R.I.P. Whitney Houston\" tribute. #IWIllAlwaysLoveYou http://shortener.twitter.com/dRc4dXH3",
"to_user": null,
"to_user_id": null,
"to_user_id_str": null,
"to_user_name": null
},
If you noticed Media under entities not available in above 2 and when i tried to call below snippet gives me null reference error
MediaUrl = (from user in tweet["entities"]["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
Same code work for Entities/URL, Hashtags and mentions but not for Media.
Also tried this -> Get JSON object node but still getting null reference exception.

In first tweet, entities object doesn't have media property, so when evaluating first tweet, your code would be equivalent to :
MediaUrl = (from user in (IEnumerable<JToken>)null
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList()
which will throw ArgumentNullException because that code does query on null reference collection.

Finally got working. Not appropriate solution but works for me.
I created separate method for parsing Media. Passed Entity as string and in that method i checked is EntityString.Contains Media or not. If yes, then parse media json else returned null. See below Snippet.
if (Entities != string.Empty)
{
if (Entities.Contains("\"media\":"))
{
JObject searchResult = JObject.Parse(Entities);
returnMedia = (from user in searchResult["media"]
select new mediaUrl
{
shortUrl = (string)user["url"],
longUrl = (string)user["expanded_url"],
url = (string)user["media_url"],
start = user["indices"][0].ToString(),
end = user["indices"][1].ToString(),
mediaType = (string)user["type"],
}).ToList();
}
}
This works for me. If you have any better solution then Please let me know.

Related

Array within Element within Array in Variant

How can I get the data out of this array stored in a variant column in Snowflake. I don't care if it's a new table, a view or a query. There is a second column of type varchar(256) that contains a unique ID.
If you can just help me read the "confirmed" data and the "editorIds" data I can probably take it from there. Many thanks!
Output example would be
UniqueID ConfirmationID EditorID
u3kd9 xxxx-436a-a2d7 nupd
u3kd9 xxxx-436a-a2d7 9l34c
R3nDo xxxx-436a-a3e4 5rnj
yP48a xxxx-436a-a477 jTpz8
yP48a xxxx-436a-a477 nupd
[
{
"confirmed": {
"Confirmation": "Entry ID=xxxx-436a-a2d7-3525158332f0: Confirmed order submitted.",
"ConfirmationID": "xxxx-436a-a2d7-3525158332f0",
"ConfirmedOrders": 1,
"Received": "8/29/2019 4:31:11 PM Central Time"
},
"editorIds": [
"xxsJYgWDENLoX",
"JR9bWcGwbaymm3a8v",
"JxncJrdpeFJeWsTbT"
] ,
"id": "xxxxx5AvGgeSHy8Ms6Ytyc-1",
"messages": [],
"orderJson": {
"EntryID": "xxxxx5AvGgeSHy8Ms6Ytyc-1",
"Orders": [
{
"DropShipFlag": 1,
"FromAddressValue": 1,
"OrderAttributes": [
{
"AttributeUID": 548
},
{
"AttributeUID": 553
},
{
"AttributeUID": 2418
}
],
"OrderItems": [
{
"EditorId": "aC3f5HsJYgWDENLoX",
"ItemAssets": [
{
"AssetPath": "https://xxxx573043eac521.png",
"DP2NodeID": "10000",
"ImageHash": "000000000000000FFFFFFFFFFFFFFFFF",
"ImageRotation": 0,
"OffsetX": 50,
"OffsetY": 50,
"PrintedFileName": "aC3f5HsJYgWDENLoX-10000",
"X": 50,
"Y": 52.03909266409266,
"ZoomX": 100,
"ZoomY": 93.75
}
],
"ItemAttributes": [
{
"AttributeUID": 2105
},
{
"AttributeUID": 125
}
],
"ItemBookAttribute": null,
"ProductUID": 52,
"Quantity": 1
}
],
"SendNotificationEmailToAccount": true,
"SequenceNumber": 1,
"ShipToAddress": {
"Addr1": "Addr1",
"Addr2": "0",
"City": "City",
"Country": "US",
"Name": "Name",
"State": "ST",
"Zip": "00000"
}
}
]
},
"orderNumber": null,
"status": "order_placed",
"submitted": {
"Account": "350000",
"ConfirmationID": "xxxxx-436a-a2d7-3525158332f0",
"EntryID": "xxxxx-5AvGgeSHy8Ms6Ytyc-1",
"Key": "D83590AFF0CC0000B54B",
"NumberOfOrders": 1,
"Orders": [
{
"LineItems": [],
"Note": "",
"Products": [
{
"Price": "00.30",
"ProductDescription": "xxxxxint 8x10",
"Quantity": 1
},
{
"Price": "00.40",
"ProductDescription": "xxxxxut Black 8x10",
"Quantity": 1
},
{
"Price": "00.50",
"ProductDescription": "xxxxx"
},
{
"Price": "00.50",
"ProductDescription": "xxxscount",
"Quantity": 1
}
],
"SequenceNumber": "1",
"SubTotal": "00.70",
"Tax": "1.01",
"Total": "00.71"
}
],
"Received": "8/29/2019 4:31:10 PM Central Time"
},
"tracking": null,
"updatedOn": 1.598736670503000e+12
}
]
So, this is how I'd query that exact JSON assuming the data is in column var in table x:
SELECT x.var[0]:confirmed:ConfirmationID::varchar as ConfirmationID,
f.value::varchar as EditorID
FROM x,
LATERAL FLATTEN(input => var[0]:editorIds) f
;
Since your sample output doesn't match the JSON that you provided, I will assume that this is what you need.
Also, as a note, your JSON includes outer [ ] which indicates that the entire JSON string is inside an array. This is the reason for var[0] in my query. If you have multiple records inside that array, then you should remove that. In general, you should exclude those and instead load each record into the table separately. I wasn't sure whether you could make that change, so I just wanted to make note.

REACT AXIOS not showing nested items

I am trying to read Midnight item in the below response
assuming it is data.timings.Midnight , but it is not showing in my react.
Is there away iterate through these nested items and show them ?
HTTP/1.1 200 OK
{
"code": 200,
"status": "OK",
"data": [{
"timings": {
"s": "03:57",
"Ss": "05:46",
"Dh": "12:59",
"Asr": "16:55",
"Sun": "20:12",
"Mag": "20:12",
"Is": "22:02",
"DATAIMintested": "03:47",
"Midnight": "00:59"
},
"date": {
"readable": "24 Apr 2014",
"timestamp": "1398332113",
"gregorian": {
"date": "15-05-2018",
"format": "DD-MM-YYYY",
"day": "15",
"weekday": {
"en": "Tuesday"
},
"month": {
"number": 5,
"en": "May",
},
"year": "2018",
"designation": {
"abbreviated": "AD",
"expanded": "Domini",
},
You are getting an array in the response. I assume you want to access the zeroeth element in the array. You can do it as below
Axios.get('<your url>')
.then(res => {
const responseData = res.data;
if(responseData && responseData.length > 0){
const midnight = responseData[0].timings.Midnight;
...
...
}
})
.catch(...)
I am guessing it is an array of objects, try to access the array's elements using indexes.Something like
axios.get(url).then(resp => {
console.log(resp.data[0].timings.Midnight);
});

Calling parse function in swift fails

I am working on a food delivery app, which uses parse as its backend. I am facing a problem while calling the placeOrder API through
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in}
Please have a look at the JSON which I need to post below.
{
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": {
"menuItems": [{
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [{
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
}],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": {
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
},
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
}],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": {
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
}
},
"unavailable_option": "restaurant_recommendation"
}
And below is the Swift code which I have used to make pass it.
let storeInfo: Dictionary = [CartStoreId: self.cartStoreId, CartStoreName: self.cartRestaurantName, CartStoreImage: self.cartStoreImage, CartStoreCuisine: self.cartStoreCuisine, CartStoreDescription: self.cartStoreDescription, CartStoreRating: self.cartStoreRating, CartStoreDelivery: self.cartStoreDelivery, Takeout: self.takeOut, Address: self.address, Slugname: self.slugName, MultipleLocation: self.multipleLocation, CartStoreDeliveryFee: self.cartStoreDelivery, CartStoreServes: self.cartStoreServes, Busy: self.busy, CartStoreSeoSlug: self.cartStoreSeoSlug] as Dictionary
let subMenuItem = ["id": "zaOo6G4KSV", "name": "Beef", "price": 12, "desc": "Fillings?", "voice_read_submi_label":"bf", "voice_read_submi_option":false, "disabled": false] as [String: Any]
let ordersDictionary = [
"id" : "1234",
"title" : "Test",
"menuTitle" : "MenuName",
"price" : 23,
"qty" : 2,
"storeId" : 23,
"orderType" : "standard",
"taxState" : 0.22,
"enable" : true,
"menuTypeName" : "Type Name",
"voice_read_mi_label":"fdfs",
"voice_read_mi_option":"false",
"submenuitem": subMenuItem,
"storeInfo": storeInfo
] as Dictionary
let timeData = ["day" : 17-06-2019, "time": "11:00 AM", "tz": "America/Los_Angeles"] as Dictionary
let data = ["menuItems": ordersDictionary, "lastOrderType": "takeout", "searchedAddress": "takeout", "timeData" : timeData] as Dictionary
let params = [UserId: self.userId, "source":"card_1EVYuOEynlyM6L4SHgBMJYRQ", "data": data, "unavailable_option":"restaurant_recommendation","_ApplicationId":"6EuadToYoFGJhI1sX8XnuFBz9tp9l3yH6HxzzXZO", "_JavaScriptKey":"rQkALu9saFtF2oq9yCibyw6mEcs3PVqct3uuP6vg", "_ClientVersion":"js1.6.14", "_InstallationId":"444ec64d-5fcc-7b8e-596e-6be627892c2a",
"_SessionToken":"r:c966376120c8eca77aa63c29d5bebe1a"] as Dictionary
After all this is done I call the parse function like below.
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in
if err != nil {
print(err!)
} else {
print(data!)
}
}
But this gives me error after a few seconds saying
"Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}"
I have searched the web with the error and made fixes accordingly but still no success. Please help me guys.
I noticed that your params var is not compatible with the JSON you sent, there are more fields and also missing fields. Moreover, menuItems and submenuItem are an Array in your JSON and an Object in your code. It is probably making the cloud code function to fail and you are therefore not receiving back a valid JSON. Try the following and check if it works. In the case it works, just replace the values by your vars.
let params = [
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": [
"menuItems": [[
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [[
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
]],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": [
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
],
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
]],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": [
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
]
],
"unavailable_option": "restaurant_recommendation"
]

Openweathermap API Forecast accessing array

So I'm trying to mess around with the openweathermap API and I can't figure out how to access some of the data.
Here the snippet of code I have that access the API.
public void find_forecast () {
String url = "http://api.openweathermap.org/data/2.5/forecast?id=4466033&appid=e4c641dd837c7947a127972091185dad&units=imperial";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray array = response.getJSONArray("list");
JSONObject object = array.getJSONObject(1);
String description = object.getString("dt");
day1.setText(description);
Here is a snippet of the API code:
{
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
],
So as you can see the code above will return the value of dt which is 1524614400. But I'm trying to access for example under "weather" the "description" which in this case is light rain. I guess I don't know how to access an array inside an array, although I couldn't even get the "temp" to return under "main", although I could get "main" to return everything underneath it.
Thanks for any help.
Max
Not sure about Android but in Javascript I would try this:
var dataObj = {
"cod": "200",
"message": 0.0042,
"cnt": 40,
"list": [
{
"dt": 1524614400,
"main": {
"temp": 63.77,
"temp_min": 63.77,
"temp_max": 64.26,
"pressure": 1017.45,
"sea_level": 1021.4,
"grnd_level": 1017.45,
"humidity": 97,
"temp_kf": -0.27
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10n"
}
]
}
]
}
console.log(dataObj.list[0].weather[0].description);
I finally figured this out. Code is below!
String array = response.getJSONArray("list").getJSONObject(0).getJSONArray("weather").getJSONObject(0).getString("description");
day1.setText(array);
This will return light rain from the API code above.

Dynamically generated metadata does not display grid

The following data is being used to load and display a grid dynamically. The only difference between the two grids is that the first reader takes in the data below as is, but the second grid only knows about the data and the metaData will be generated on the fly. I placed stubs for the fields and columns as this is not the issue and I haven't decided on how I will generate the data yet.
Both of the readers eventually pass the data below to the JsonReader's readRecords()' function via this.callParent([data]);, but the second one does not display the data. The data is there, but I am not sure why it does not display?
There are two links to demos below. The first is a JSFiddle that loads from memory and the second is a Sencha Fiddle that loads through AJAX.
Snippet
var rawFields = [
{ "name": "year", "type": "int" },
{ "name": "standard", "type": "string" },
{ "name": "bitRate", "type": "float" }
];
var rawColumns = [
{ "text" : "Year", "dataIndex" : "year", "flex" : 1 },
{ "text" : "Standard", "dataIndex" : "standard", "flex" : 1 },
{ "text" : "Bit/Sec", "dataIndex" : "bitRate", "flex" : 1 }
];
Ext.define('Example.reader.DynamicReader', {
extend : 'Ext.data.reader.Json',
alias : 'reader.dynamicReader',
readRecords : function(data) {
var response = {
data: data,
metaData : this.createMetaData(data),
success: true
};
console.log(response);
return this.callParent([response]);
},
createMetaData : function(data) {
return {
idProperty : "id",
fields : rawFields, // These will eventually be generated...
columns : rawColumns // These will eventually be generated...
};
}
});
Data
{
"data": [
{
"id": 0,
"year": 1997,
"standard": "802.11",
"bitRate": 2000000
},
{
"id": 1,
"year": 1999,
"standard": "802.11b",
"bitRate": 11000000
},
{
"id": 2,
"year": 1999,
"standard": "802.11a",
"bitRate": 54000000
},
{
"id": 3,
"year": 2003,
"standard": "802.11g",
"bitRate": 54000000
},
{
"id": 4,
"year": 2007,
"standard": "802.11n",
"bitRate": 600000000
},
{
"id": 5,
"year": 2012,
"standard": "802.11ac",
"bitRate": 1000000000
}
],
"metaData": {
"idProperty": "id",
"fields": [
{
"name": "year",
"type": "int"
},
{
"name": "standard",
"type": "string"
},
{
"name": "bitRate",
"type": "float"
}
],
"columns": [
{
"text": "Year",
"dataIndex": "year",
"flex": 1
},
{
"text": "Standard",
"dataIndex": "standard",
"flex": 1
},
{
"text": "Bit/Sec",
"dataIndex": "bitRate",
"flex": 1
}
],
"success": true
}
}
Demos
The following examples both achieve the same thing, so the only difference is the loading of the data.
Loading from Memory
http://jsfiddle.net/MrPolywhirl/zy4z5z8a/
Loading from AJAX
https://fiddle.sencha.com/#fiddle/d3l
I figured out the answer. I needed to specify a root value for the reader so that the data can be mapped properly.
Ext.onReady(function() {
Ext.widget("dynamicGrid", {
title: 'WiFi LAN Data Rates [Dynamic]',
renderTo: Ext.get('example-grid-dynamic'),
readerType: 'dynamicReader',
// This need to match the 'data' key specified in the `response` object
// that was created in readRecords().
readerRoot: 'data',
data : rawData
});
});
The documentation for root notes that the root property has to map to the data portion of the response.
Documentation for Json.root:
Ext.data.reader.Json.root
root : String
The name of the property which contains the data items corresponding to the Model(s) for which this Reader is configured. For JSON reader it's a property name (or a dot-separated list of property names if the root is nested). For XML reader it's a CSS selector. For Array reader the root is not applicable since the data is assumed to be a single-level array of arrays.

Resources