I am fiddling with some a script for Fiddler, which uses JScript.NET. I have a string of the format:
{"params":{"key1":"somevalue","key2":"someothervalue","key3":"whatevervalue", ...
I want to match and show "key2":"someothervalue"
where someothervalue
could be any value but the key is static.
Using good old sed
and bash
I can replace the part I am looking for with:
$ a='{"params":{"key1":"somevalue","key2":"someothervalue","key3":"whatevervalue", ...'
$ echo $a | sed -r 's/"key2":"[^"]+"/replaced/g'
{"params":{"key1":"somevalue",replaced,"key3":"whatevervalue", ...
Now. Instead of replacing it, I want to extract that part into a variable using JScript.NET. How can that be done?
The most graceful way is to use a JSON parser. My personal preference is to import IE's JSON parser using the
htmlfile
COM object.Compiling, linking, and running results in the following console output:
Alternatively, there are also at least a couple of .NET namespaces which provide methods to serialize objects into a JSON string, and to deserialize a JSON string into objects. Can't say I'm a fan, though. The ECMAScript notation of
JSON.parse()
andJSON.stringify()
are certainly a lot easier and profoundly less alien than whatever neckbeard madness is going on at Microsoft.And while I certainly don't recommend scraping JSON (or any other hierarchical markup if it can be helped) as complicated text, JScript.NET will handle a lot of familiar Javascript methods and objects, including regex objects and regex replacements on strings.
sed syntax:
JScript.NET syntax:
JScript.NET, just like JScript and JavaScript, also allows for calling a lambda function for the replacement.
... Or to extract the value of
key2
using theRegExp
object'sexec()
method:Just be careful with that, though, as retrieving element
[1]
of the result ofexec()
will cause an index-out-of-range exception if there is no match. Might either want toif (/"key2":/.test(a))
or add atry...catch
. Or better yet, just do what I said earlier and deserialize your JSON into an object.