Home > Software design >  Creating cookies from Json file - does the type of the value matter?
Creating cookies from Json file - does the type of the value matter?

Time:06-11

I exported my cookies in a Json file. It looks like this:

[
    {
        "name": "abc",
        "value": "0000",
        "domain": ".domain.com",
        "hostOnly": false,
        "path": "/",
        "secure": false,
        "httpOnly": false,
        "sameSite": "no_restriction",
        "session": false,
        "firstPartyDomain": "",
        "partitionKey": null,
        "expirationDate": 1734526188,
        "storeId": null
    },
    {
        "name": "dfg",
        "value": "777",
        "domain": ".domain.it",
        "hostOnly": false,
        "path": "/",
        "secure": true,
        "httpOnly": true,
        "sameSite": "no_restriction",
        "session": false,
        "firstPartyDomain": "",
        "partitionKey": null,
        "expirationDate": 1684947948,
        "storeId": null
    }
]

As you can see, there are some values which are strings, such as name, hostOnly is a boolean, partitionKey is a nullable and expirationDate is an integer.

This is the C# code I am using

json = File.ReadAllText("json.txt");
JArray array = JArray.Parse(json);

foreach(JObject cookie_json in array)
{
      foreach(var entry in cookie_json)
      {
         cookies.Add(new Cookie(entry.Key, (string?)entry.Value));
      }
 }

But here I find a couple of errors:

  1. Cookie() constructor accepts only strings as Value and so I am not able to add integers, booleans and not nullable elements, 'cause a nullable will throw an Exception
  2. I am creating a new Cookie for each entry (row) not for each Json element (representing one cookie). How can I fix that?

CodePudding user response:

I can see your logic - if you drill down into openqa.selenium.cookie you can see how they've implemented the constructors:

        public Cookie(string name, string value, string domain, string path, DateTime? expiry)
        public Cookie(string name, string value, string path, DateTime? expiry)
        public Cookie(string name, string value, string path)
        public Cookie(string name, string value)

You don't add each individual part of the cookie - you'd create the cookie by declaring all the values at once.

All the values in a cookie are strings so you'll just need to .toString() and non-string values.

Looking at your JSON - I'm not sure how you got storeID. storeId isn't a cookie parameter - see here for more info: cookieobject

You can also add/manipulate cookies directly though JS in the console with something like document.cookie = "MyName=myValue;StoreId=123" (and it's worth noting you can do this with Selenium too)

But when you add unrecognised values it just rips them out: devtoolsconsole

Potentially that could be it's own cookie? - but now I'm just guessing. Can you share more info around where that value is from if you need more support?

  • Related