0

I need to parse in C# (key ,value wise) a string that is built in a JSON format (to be exact I need to parse the binding parameter of Knockout data-bind). I go over the html file and I extract the bindings. I want to modify each and every binding (string-wise), but It's really hard for me to parse the string, since I can't really know where each binding stops and the other starts.

for example:

data-bind="text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"

will result in the following string:

"text:'ggggg',event:{mouseover:x=function(){alert(1);return 'd,y'}}"

I want to modify the string in the following way:

newString= "text('gggg'),event(mouseover(x=function(){alert(1);return 'd,y'}))"

I figured out that the best way to do it is to deserialize the string by JSON and then it will be easier for me to get access to each and every binding element. I write at C#, but since I go over the html file and each data-bind is different and can contain different amount and type of attributes I would like to have a general object that I can deserialize to. I checked out DataContractJsonSerializer but I don't see how it solves my problem. Can you please suggest me what's best for my case? Mary

mary
  • 869
  • 5
  • 13
  • 26
  • For Json deserialization use Json.Net Library. You can deserialize to a `dynamic` object:http://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-neto or an anonymous type and access the fields you need. On the other hand, maybe using Regular Expressions would be enough? – qbik Jun 17 '14 at 11:46
  • The thing is that I can't really use regex because the string might contain javscript code- any code. Does JSON.Net library can work with x:y when they are not represented as strings? – mary Jun 17 '14 at 11:54
  • 2
    Dude, you will never be able to deserialize functions and AD-HOC code from a JavaScript JSON object into a C# class. – Adrian Salazar Jun 17 '14 at 12:08
  • ok so what can you suggest me to do ? – mary Jun 17 '14 at 12:48
  • Why exactly do you need to do that? Maybe we can figure out another way than parsing your html. It will be very complicated to get rid of the javascript, since all the bindings in ko can be javascript expressions – GôTô Jun 17 '14 at 13:17
  • Functions are not legal JSON. – Kyeotic Jun 17 '14 at 15:43
  • @Tyrsius thought so, didn't dare to say :) – GôTô Jun 17 '14 at 15:57

1 Answers1

0

You can do it with something like this:

var obj = ko.bindingProvider.instance.getBindings(yourDomElement,
                                                ko.contextFor(yourDomElement));
alert(JSON.stringify(obj));

And then do whatever you want with obj.

Fiddle

But... well... don't!

GôTô
  • 7,974
  • 3
  • 32
  • 43