Changing json query delimiter with Json.net - c#

I'm working with Newtonsoft Json and in order to query a json string, I use the SelectToken method which uses "." as a delimiter to query the hierarchy of the json as described in the docks:
https://www.newtonsoft.com/json/help/html/SelectToken.htm
Is there some way to change the delimiter from using "." to using ":"? meaning that instead of querying for example "a.b.c", I could query for "a:b:c"? It doesn't have to use the SelectToken, but I still got to have a way to reach a specific path with given keys (like the a,b,c in my example above)

No, there is no way to change it. The argument provided to SelectToken is a path which Json.Net internally parses and converts to JPath. If you check the source for same, you can see . is hardcoded as one of the switch-cases in ParsePath method of JPath class. Check here
and here too.

Related

Maintaining source string format when reading a date-time from a JSON path and writing it to another file

How can I have Newtonsoft.Json read the value of a path without converting or otherwise meddling with values?
This code
jsonObject.SelectToken("path.to.nested.value").ToString()
Returns this string
03/07/2019 00:02:12
From this string in the JSON document
2019-07-03T00:02:12.1542739Z
It's lost its original formatting, ISO 8601 in this case.
I would like all values to come through as strings, verbatim. I'm writing code to reshape JSON into other formats and I don't want to effect the values as they pass through my .NET code.
What do I need to change? I am not wedded to Newtonsoft.Json btw.
I got it, I think.
jsonObject.SelectToken(path).ToString(Newtonsoft.Json.Formatting.None);
The other options were to supply nothing or this.
Newtonsoft.Json.Formatting.Indented
Which is strange logic in this API as you'd think None means not indented but it means not ... I don't know. Hang on....
Okay so None or Indented returns
"2019-07-03T00:02:12.1542739Z"
(including quotes) but using the overload taking no parameters returns
03/07/2019 00:02:12
That's an odd API design ¯\_(ツ)_/¯
Here's a screenshot which shows really simple repro code.

how to convert lambda expressions into json string

I have two applications. One application saves options and configurations down as JSON and the other reads the JSON and performs it's task based on the fields in the JSON. Now I want to filter a list that is in application-2. How can I pass how I want the list to be filtered into a string to be stored in JSON and then reinterpreted by application-2?
Is there anyway to serialize linq/lambda expressions and deserialize them? Or is there a better approach like creating a class that contains some filterable options like equal-to, not-equal-to, greater-than, less-than, contains, etc?
Unfortunately there is no way to serialize and serialize a lamda expression in c#, because it is make in compile time.
The Lamda after the compilation generates a function and the compiler call this function when the lamda expression is used.
You have one option, but is not easy :) Yoy have to store a c# code in json file, and the application-2 will read it, parse it, compile it, and execute it.
But itt will be a complete assembly (like one class) not only one lamdba expression.
If you use :net framrwork here is an example:
https://www.codeproject.com/Tips/715891/Compiling-Csharp-Code-at-Runtime
If you use .Net Core, teh ypu have to use roslyn: https://josephwoodward.co.uk/2016/12/in-memory-c-sharp-compilation-using-roslyn
I hope it helps
regrads
I found for another solution for this problem. You can store and revert an Expression from string! :)
The only need, the two module (or two program in your case) must be the known the same type.
Sample code:
var discountFilter = "album => album.Quantity > 0";
var options = ScriptOptions.Default.AddReferences(typeof(Album).Assembly);
Func<Album, bool> discountFilterExpression =
await CSharpScript.EvaluateAsync<Func<Album, bool>>(discountFilter, options);
var discountedAlbums = albums.Where(discountFilterExpression);
Regrads
gy
If you want to filter javascript arrays in pure JSON, you can use Jpath and Json.Net
For example:
var token = JToken.Parse("json string here")
var tokens = token.SelectTokens("$.YourJsonArray[?(#.Property == something)]")

How to deserialize in C# an unknown JSON string to some Object

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
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!

How to parse JSON results in to a dynamic object

I'm trying to write a C# utility to consume the results returned from the Export API by MailChimp.
The documentation states that the results will be returned as "streamed JSON."
"This means that a call to this API will not return a single valid JSON
object but, rather, a series of valid JSON objects separated by
newline characters."
The results that I'm seeing don't look like normal JSON to me, and aren't what I was expecting to be working with. It looks to me like CSV data wrapped in square brackets, with row headers in the first line.
A snip of the results can be viewed here. I'll paste them below as well.
["Email Address","First Name","Last Name","Company","FirstOrder","LastOrder","CustomerID","SalesRep","ScreenName","PlayerPage","PlayerPDF","Services Purchased","Contests","EMAIL_TYPE","MEMBER_RATING","OPTIN_TIME","OPTIN_IP","CONFIRM_TIME","CONFIRM_IP","LATITUDE","LONGITUDE","GMTOFF","DSTOFF","TIMEZONE","CC","REGION","LAST_CHANGED","LEID","EUID"]
["john#domain.com","John","Doe","ACME Inc","2010-09-07","2010-09-07","ABC123","sally","","","","Service1","","html",2,"",null,"2011-12-23 15:58:44","10.0.1.1","34.0257000","-84.1418000","-5","-4","America\/Kentucky\/Monticello","US","GA","2014-04-11 18:38:39","40830325","82c81e14a"]
["jane#domain2.com","Jane","Doe","XYZ Inc","2011-05-02","2011-05-02","XYZ001","jack","","","","Service2","","html",2,"",null,"2011-12-23 15:58:44","10.0.1.1","34.0257000","-84.1418000","-5","-4","America\/Kentucky\/Monticello","US","GA","2014-04-11 18:38:40","40205835","6c23329a"]
Can you help me understand what is being returned -- as it doesn't appear to be normal JSON. And what would be my best approach to parse this stream of data into a C# object.
EDIT: I've confirmed that the data stream is valid JSON using http://www.freeformatter.com/json-validator.html and pasting in the sample lines above. So what I'm hoping for is a way to dynamically create an object based on the first line, then create a list of these objects with the values contained in the subsequent lines.
You are correct, this is not in typical JSON form. What you could do is create a collection of Dictionary<string, string> objects. Use the first part of the response to use as the keys of the dictionaries and then the values found in subsequent pieces of the result as the values of each dictionary.

converting json string into json on client side?

In my javascript code I am getting json string from cs file
var tmpString="<%=resultset2%>";
In cs I am concatenating strings to build json string. Here is an issue the json string is returned as a string and it has " with it.
"[{id:'1',name:'Aik'},{id:'2',name:'Aik or Aik'}]"
Because of " in beginning and end javascript code treat it as a string. Kindly guide me how I should sort out this issue.
thanks
Fix the JSON, it has errors (property names must be strings (and thus quoted), and only " are acceptable for quoting strings in JSON). JSON is a subset of JavaScript, you can't use all of JS' syntax in JSON. As a rule of thumb, if you are concatenating strings to produce a data format, then you are doing it wrong. http://json.org/ lists a number of C# libraries that you can use to build JSON.
Use json2.js
Change this:
var tmpString="<%=resultset2%>";
to:
var tmpString=<%=resultset2%>;
This isn't JSON, you're just writing javascript from a server page. The problem is you are creating invalid javascript syntax, you just need to remove the quotes.
The quotes aren't from resultset2 they are from your markup.

Categories