PowerShell Parse Non-Standard JSON - json

I have some JSON like config files that I need to parse... They look something like
{
"_Comment":"This is not valid, but required or it breaks the program",
"_Comment":"If there is only one of these, standard Converters work",
"_Comment":"But, there are multiple of these lines",
"Name":"Some Body",
"Address1":"123 Name of Street",
"City":"Some Town",
"ST":"AZ",
"Zip":"01234-5678",
"ItemCount": 101
}
If I strip out the "_Comment" and "_Comments" lines, it parses correctly, but if I save it and don't put the "_Comment" and "_Comments" lines back, it breaks the application that uses the info.
Any suggestions on how I can strip out and put back those _Comment and Comments lines, or should I take a different approach?
This project requires that I use PowerShell; however, I can port from many languages, c, c++, c#, pascal, java script, vbscript, etc. Pseudo code is just as good as real code to me.
Thanks!

Related

How to use JSON Utility to Import Data from Browser to Unity?

I am just getting started programming and I couldn’t wrap my head around the following problem I currently have:
I have a PHP Script which retrieves the CPU Temperature of a Raspberry Pi and shows it on a local Network in my browser. The output in my browser is just a blank page with the value e.g. 56.7 only and no more.
What I would like to know now is, if it’s possible with JSON Utility to take this value and import it into Unity -> to be more specific, into an Augmented Reality Environment using Vuforia, even if it’s on a local Network and the only output is just the temperature value.
Is there anyone who could answer these (probably trivial) questions and eventually could show me how the code could look like?
And is it correct to assume, that the value within Unity would change as soon as the value in my browser changes?
I would like to thank everyone in advance for any help at all and even though these questions seem obvious for experienced programmers, I wasn’t able to find a correct answer by now.
Best regards!
Use UnityWebRequest to contact your Raspberry Pi.
Parse the DownloadHandler.text any way you like. JSON Utility is one option for parsing the result, but it might be overkill if this is a hobby project that just gets one sensor value.
https://docs.unity3d.com/Manual/UnityWebRequest-RetrievingTextBinaryData.html
To parse the json with JsonUtility, you would make a class to hold the data, making sure to mark it with Serializable attribute.
[System.Serializable]
public class MyData
{
public float temperature;
}
And then parse it like this, in the RetrievingTextBinaryData example
MyData myData = JsonUtility.FromJson<MyData>(www.downloadHandler.text)
Assuming your JSON looks like this
{ "temperature":30.7 }
Note: to make it continuously poll your Raspberry Pi for updates, you would need to download the temperature in the Update() method instead of Start() like in the example code.

Is there an Actionscript to ABC Bytecode parser?

So, I have an app where users should define ActionScript functions.
What do I need to get the string whritten by the user and convert it to bytecode so that I can use it with as3-commons-bytecode?
Edit
I don't think I was clear enough. I need to turn: if(!myValue) {...}
Into this:
...
findpropstrict private::myValue
getproperty private::myValue
not
iffalse L1
...
Because with this ^^^^ code, I can use as3-commons-bytecode to do what I need.
I took a look at this app's source code. It's very confusing, the project is old and the code is a mess, but it works. I need to find "where the magic happens". Can you show me the way?
You should use part of this project :
eval.hurlant.com/demo/#app=da4a&757d-selectedIndex=0
Check source , there is parser to ABC .
I'm not aware of any libraries that do this for you, but to achieve this functionality you should parse user's input into function names.
For example, you can call a function just by having it's name as a String like so:
var functionName:String = "myMethod";
function myMethod():void
{
trace("myMethod");
}
this[functionName](); //traces "myMethod"
Of course, if you wish to interpret advanced strings with getting/setting objects and their properties and any other user defined statements, that would require to write quite a sophisticated string-to-bytecode converter.
UPDATE:
There's also AS3Eval library that might do the job. Take a look at http://eval.hurlant.com/
There is a library for Haxe which makes it possible to compile Actionscript assembly language into ABC at runtime, but this is still lower-level than the Actionscript you normally write.
http://haxe.org/com/libs/format/abc
The most likely solution is a server or other process which can compile and return SWF content for you. Haxe has a very fast and straightforward compiler, but it may also be possible to use Tamarin or another solution for compiling AS3 on the server.
Actually, there is a runtime library for executing Haxe code, which again, is very similar to Actionscript. Might be worth looking into:
http://code.google.com/p/hscript/
What exactly want to do? To compile "string" the string must be something meanfull for the compiler such as package not a simply string ( like 'asdas ' ). If you don't wont to use flash/flex compiler you may compile AS to ABC with Ant or Haxe. But ther is a problem - how you will start this ABC?

How do you implement odd business needs?

We provide web services that'll return informations about a product like this (simplified)
<product>
<id>123</id>
<name>Mobil-home</name>
<pricing>
<price>12</price>
<adults>2</adults>
</pricing>
<pricing>
<price>15</price>
<adults>3</adults>
</pricing>
</product>
Our partner says "Our problem is that in our system we can have only 1 adult count per product". This partner is working with a huge system, and they say that it's a big problem and they can't change anything about it in their side.
So what did we decide ? to explode our results like this
<product>
<id>123</id>
<virtualId>123#2</virtualId>
<name>Mobil-home</name>
<pricing>
<price>12</price>
<adults>2</adults>
</pricing>
</product>
<product>
<id>123</id>
<virtulId>123#3</virtualId>
<name>Mobil-home</name>
<pricing>
<price>15</price>
<adults>3</adults>
</pricing>
</product>
So we created a "virtualId" that concatenate the id and the adults with an #. Technically it's a mess, but we do software for a business, the target is not to make clean software, but to make money.
My solutions are :
I try to make a concept out of it : "In some call I have to call a service class that'll explode our results", and then add this functionality to my web service (even if I'm sure we'll use this only in the case of this partner).
I do 3 dirty lines of code with an ugly (if user == "thispartner")
I add a layer between my partner and my web service that'll do the ugly job
I'm stubborn and I say to my boss "We can't work with them, our systems are not compatible", and then I go to the Pole Emploi.
How do you deal in these cases ?
I think the best technical solution will really depend on your implementation, so it isn't really language-agnostic.
For example, if you use a language with full reflection, like Python, my solution would be to add a database field to the partner list named something like TransformationClass. Then, your web service code would look something like:
output = do_normal_processing()
if partner.TransformationClass is not null:
transformation = construct an instance of the partner.TransformationClass class
output = transformation.transform(output)
return output
(Note: for Python, you can construct an instance based on a classname like this.)
You can then create a source code subdirectory 'clientSpecificTransformations' and dropper-client transformations in there; no need to even recompile or restart anything.
However, IMHO for languages that lack the reflection to do such a thing, you'll end up jumping through hoops, and I'd just write a specific proxy for that client and instruct him to use the proxy's URL. The proxy can just make the exact same request to the original service and then explode as required.

General approach to reading lnk files

Several frameworks and languages seem to have lnk file parsers (C#, Java, Python, certainly countless others), to get to their targets, properties, etc. I'd like to know what is the general approach to reading lnk files, if I want to parse the lnk in another language that does not have said feature. Is there a Windows API for this?
There is not an official document from Microsoft describing lnk file format but there are some documents which have description of the format. Here is one of them: Shortcut File Format (.lnk)
As for the API you can use IShellLink Interface
Simply use lnk file parser at J.A.F.A.T. Archive of Forensics Analysis Tools project.
See lnk-parse-1.0.pl at http://jafat.sourceforge.net
There seems no have no dependencies. Syntax is simple and link file becomes a simple text in standard output and to be usable on Linux.
This is an old post, but here is my C# implementation for lnk processing that handles the entire spec, more info and command line tool on this blogspot page.
Using WSH-related components seems the most convenient option to read .lnk files in most languages on a post-XP windows system. You just need access to the COM environment and instantiate the WScript.Shell Component. (remember that on win, references to the Shell usually refer to explorer.exe)
The following snippet, e.g. does the thing on PHP: (PHP 5, using the COM object)
<?php
$wsh=new COM('WScript.Shell'); // the wsh object
// please note $wsh->CreateShortcut method actually
// DOES THE READING, if the file already exists.
$lnk=$wsh->CreateShortcut('./Shortcut.lnk');
echo $lnk->TargetPath,"\n";
This other one, instead, does the same on VBScript:
set sh = WScript.CreateObject("WScript.Shell")
set lnk = sh.CreateShortcut("./Shortcut.lnk")
MsgBox lnk.TargetPath
Most examples in the field are written in VB/VBS, but they translate well on the whole range of languages supporting COM and WSH interaction in a form or another.
This simple tutorial may come handy, as it lists and exemplifies some of the most interesting properties of a .lnk file other than the most important: TargetPath. Those are:
WindowStyle,
Hotkey,
IconLocation,
Description,
WorkingDirectory
here's some C# code using the Shell32 API, from my "ClearRecentLinks" project at https://github.com/jmaton/ClearRecentLinks
To use this your C# project has to reference c:\windows\system32\shell32.dll
string linksPath = "c:\some\folder";
Type shell32Type = Type.GetTypeFromProgID("Shell.Application");
Object shell = Activator.CreateInstance(shell32Type);
Shell32.Folder s32Folder = (Shell32.Folder)shell32Type.InvokeMember("NameSpace", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { linksPath });
foreach (Shell32.FolderItem2 item in s32Folder.Items())
{
if (item.IsLink)
{
var link = (Shell32.ShellLinkObject)item.GetLink;
if (link != null && !String.IsNullOrEmpty(link.Target.Path))
{
string linkTarget = link.Target.Path.ToLower();
// do something...
}
}
}
#Giorgi: Actually, there is an official specification of lnk files, at least it is claimed so.
However, for some reason, the link seems to be dead, and after downloading the whole (45 MB) doc package (Application_Services_and_NET_Framework.zip), it appears that it does not include the file MS-SHLLINK.pdf.
But is this really surprising ?
Once you got the file format, shouldn't be too hard to write code to read it.

Is using advanced constructs (function, new, function calls) in JSON safe?

JSON is a nice way to pass complex data from my server side code to client side JavaScript. For example, in PHP I can write:
<script type="text/javascript>
var MyComplexVariable = <?= BigFancyObjectGraph.GetJSON() ?>;
DoMagic(MyComplexVariable);
</script>
This is pretty cool, but sometimes you want to pass more than basic date, like dates or even function definitions. There is a simple and straightforward way of doing it too, like:
<script type="text/javascript>
var MyComplexVariable = {
'SimpleProperty' : 42,
'FunctionProperty' : function()
{
return 6*7;
},
'DateProperty' : new Date(989539200000),
'ArbitraryProperty' : GetTheMeaningOfLifeUniverseAndEverything()
};
DoMagic(MyComplexVariable);
</script>
And this works like a charm on all browsers I've seen so far. But according to JSON.org such syntax is invalid. On the other hand, I've seen this syntax being used in very many places, including some popular JavaScript frameworks. So...
Can I expect any problems if I use "unsupported" JSON features like the above? Why is it wrong or not?
Added clarification: If I expected my JSON to be consumed by some unknown 3rd party software, or even a known parser which was not a browser, then such exotics would indeed most likely not work and I would not attempt to embed them. But I'm interested in the case where the JSON code is written directly inside a JavaScript code block that is executed by an Internet browser. Like the examples above.
According to JSON.org, a JSON object only supports the following value members of an object:
(source: json.org)
Since none of these is a function, I would suggest not using it since, as you said, it is not officially supported in the spec.
Besides, what happens when a non-Javascript client (such as a Python program) tries to consume your JSON? How is it going to run your JavaScript code?