Parsing a string, using action script - actionscript-3

I am working on a flex site,
I want to parse the string below:
http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download_picture&key=a4fb33241662c35fe0b46c7e40a5b416&session_id=2b7075f175f599b9390dd06f7b724ee7
and remove the &session_id=2b7075f175f599b9390dd06f7b724ee7 from it.
How should i do it.
also later on when i get the url from database without session_id, i will attach the new session_id to it. Please tell me how to do that too.
Regards
Zeeshan

Not the short version but you can use URLVariable to get all the field(name, value) into an object and then add or delete any field you want.
Separate url and query:
var url : String = "http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download%5Fpicture&key=a4fb33241662c35fe0b46c7e40a5b416&session%5Fid=2b7075f175f599b9390dd06f7b724ee7";
var idxQMark : int = url.indexOf("?");
var qry : String = "";
Build url variable from query
var uv : URLVariables = new URLVariables();
if (idxQMark > 0) {
qry = url.substr(idxQMark + 1);
url = url.substr(0, idxQMark);
uv.decode(qry);
}
NOw you can access whatever field you need or delete them
delete uv.session_id;
Rebuild the query when needed
qry = uv.toString();
// get back you new URL
if (qry != "") {
url = url + "?" + qry;
}

For URI parsing check out the URI class provided in as3corelib.
http://code.google.com/p/as3corelib/source/browse/trunk/src/com/adobe/net/URI.as
For your specific case, you can clear the parts of the URI you don't want.
var url : String = "http://virtual.s1.c7beta.com/rpc/raw?c=Pictures&m=download%5Fpicture&key=a4fb33241662c35fe0b46c7e40a5b416&session%5Fid=2b7075f175f599b9390dd06f7b724ee7";
var uri : URI = new URI(url);
uri.query = "";
uri.fragment = "";
var shortenedUrl : String = uri.toString();
Or if you know you want to construct your url from just the scheme, authority, and path (i.e., you don't need to preserve port, username, password, etc.) you can build the url from parts.
var shortenedUrl : String = uri.scheme + "://" + uri.authority + "/" + uri.path;

If you're not sure that sessionid will be last you could split on the & using the as3 string.split functionhttp://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html#split%28%29
then rebuild the string using a for loop leaving out strings that start with session_id using the string.indexOf function http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html#indexOf%28%29 to see if "session_id" is at index 0

You can use regular expressions in Flex ... here's an example.

Assuming the session ID will always be the last variable in the query string:
var newStr:String = myStr.slice(0, myStr.indexOf("&session"));

Related

Convert and parse json string to key value pairs using NewtonSoft

Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.
Response from the API:
var response = #"{'result':{'0199 - B344EE33':
{
'6400_00260100':{'1':[{'val':336688}]},
'6400_00462500':{'1':[{'val':null}]},
'6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";
Result I want is a new object of key value pairs:
{
"6400_00260100" : 336688,
"6400_00462500" : null,
"6800_00832A00" : 3000,
"6800_008AA200" : 0
}
In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.
What I have is the following but for getting the key value pairs in a clean way I got stuck:
var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;
UPDATE
var jObjectResult = new JObject();
var response = #"{'result':{'0199 - B344EE33':
{
'6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
'6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
'6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_08822B00':{'1':[{'val':'SMA'}]},
'6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
}}}";
var json = JObject.Parse(response);
var json_serial = json["result"].First.Children<JObject>().ToList()[0];
foreach(var token in json_serial)
{
var tokenKey = token.Key;
var tokenVal = token.Value.SelectToken("$.1[0].val");
jObjectResult.Add(tokenKey, tokenVal);
}
You could use SelectTokens with the recursive descent operator .. to find all the val properties, then walk up the chain using .Parent repeatedly to get the corresponding key. Create new JProperties from this information and put them into a new JObject to get your result. Here is a "one-liner":
var result = new JObject(
JObject.Parse(response)
.SelectTokens("$..val")
.Select(jt => new JProperty(
((JProperty)jt.Parent.Parent.Parent.Parent.Parent.Parent).Name,
jt
))
);
Fiddle: https://dotnetfiddle.net/TbZ7LS
At the end with some pointers form #Brian Rogers I came with the following solution:
// Arrange
var response = #"{'result':{'0199 - B344EE33':
{
'6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
'6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
'6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
'6800_08822B00':{'1':[{'val':'SMA'}]},
'6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
}}}";
// Act
var json = JObject.Parse(response);
var json_serial = (JProperty)json["result"].First();
var jObjectResult = new JObject(
json_serial.Value.Select(p =>
{
return new JProperty(
((JProperty)p).Name,
p.First.SelectToken("$.1[0].val")
);
}));

MVC - model to a json object

I had a mvc object as my model.
I need to stringfiy my model as a json object type - and then use it in js as i please.
i currently doing something like this
<script type="text/javascript">
$(function () {
var jsonData2 = '#Html.Raw(Json.Encode(Model))';
showBeginDate(jsonData2);
});
</script>
But when i try to acess a json property for exemple as jsonData2.BeginDate I keep getting undefined.
jsonData2 is a json object - why can i "read" from it?
Regards
#riteshmeher 's suggestion is correct
var text = '#Html.Raw(Json.Encode(Model))';
var obj = JSON.parse(text);
I don't know your model so I created a simple model with 2 attributes: Id and Name. In case that the model is a list, you can read it:
// Access to object in position 1
var result = obj[0].Id + " - " + obj[0].Name;
In other case, access right to the property.
var result = obj.Id + " - " + obj.Name;
For more info, check this post:
http://www.w3schools.com/js/js_properties.asp
http://www.w3schools.com/json/tryit.asp?filename=tryjson_parse
UPDATE
like #Stephen Muecke said, better this:
var obj = #Html.Raw(Json.Encode(Model));
var result = obj[0].Id + " - " + obj[0].Name;
thank #Craig for the corrections

Convert text string to hexadecimal using flash builder

I want to convert MAC Address into hexadecimal string using flash builder..
I used this code
var networkInterface : Object = NetworkInfo.networkInfo.findInterfaces();
var networkInfo : Object = networkInterface[0];
var physicalAddress : String = networkInfo.hardwareAddress.toString();
txtreq.text = physicalAddress + "-" + txtserial.text
var reqcode:uint = uint(txtreq.text);
var reqcode1:String = reqcode.toString(16);
txtact.text = reqcode1;
When I run the application,
txtserial.text = 123 and physicalAddress = C6-17-31-A9-EF-FF...
but txtact.text got 0.
Then how I fix the problem and In flex Builder how I convert FF-FF-FF-FF-FF like text into hexadecimal code...
You should use parseInt(reqcode,16) instead of reqcode.toString(16);

Replace text surrounded by *** with <b> and </b>

Let's say I have a string
var myString: String = "This ***is*** my ***string***"
Now I'm searching for a way to replace the stars with html-bold tags.
After replacement the code should look like:
"This <b>is</b> my <b>string</b>
What I've done so far:
var boldPattern : RegExp = /\*\*\*.*?\*\*\*/;
while(boldPattern.test(goalOv[gCnt][1])){
myString = myString.replace(boldPattern, "<b>"+myString+"</b>");
}
This ends up with an endless Loop (because I'm assigning the string to itself).
Thanks
I'm not good at regular expressions, but I think this simple solution will do the trick:
var boldPattern : RegExp = /(\*\*\*)/;
var myString: String = "This ***is*** my ***string***";
var count:int = 0;
while(boldPattern.test(myString))
{
if(count % 2 == 1)
myString = myString.replace(boldPattern, "</b>");
else
myString = myString.replace(boldPattern, "<b>");
count++;
}
As Gio said, that looping isn't the best way of replacing globally. You should instead do the following to avoid looping and have replacement in one pass over the string.
var boldPattern :String = "This ***is*** my ***string***";
var myString:RegExp = /\*\*\*([^*]*)\*\*\*/g;
var replText:String = "<b>$1</b>";
myString = myString.replace(boldPattern, replText);
Also, if you want to do it more correctly to allow for myString have have string of 1 or 2 *, you can use:
/\*\*\*(([^*]+\*{0,2})+)\*\*\*/g

Reverse engineering - Flash app

I have that code:
private function handleFlashVarsXmlLoaded(event:Event) : void
{
var secondsplit:String = null;
var item:Array = null;
var string:* = XML(String(event.target.data));
var notsplited:* = string.vars_CDATA; //what is .vars_CDATA?
var splitted:* = notsplitted.split("&");
var datacontainer:Object = {};
var index:Number = 0;
item = secondsplit.split("=");
datacontainer[item[0]] = item[1];
this.parseFlashVars(datacontainer); // go next
return;
}
That function is loaded when URLLoader is loaded.
I think that this function parse a XML file to string(fe. param1=arg1&param2=arg2), then split it by "&" and then by "=" and add data to datacontainer by
datacontainer["param1"] = "arg1"
But how should the XML file look like and what is string.vars_CDATA
I think, vars_CDATA is just a name of XML field, becourse variable named "string" is contains whole XML. So var "notsplited" contains a String-typed data of this field (I think so, becourse of the line "var splitted:* = notsplitted.split("&");", which splits String to Array).