Dynamically convert string to object

c# dynamic object
serialize dynamic object c#
c# dynamic type casting using reflection
c# dynamic object add property
c# dynamic to dictionary
c# dynamic json check if property exists
c# dynamic property name
c# dynamic list

I have an API returning the following string

styles: "background #2b2b2b; color: #FFFFFF"

I need to convert this on the fly into an object like so

styles: { background: '#2b2b2b', color: '#FFFFFF' }

How best to achieve this

Regular expression alternative https://regex101.com/r/ZmAW1m

var o = {}, s = "background #2b2b2b; color: #FFFFFF"

s.replace(/([^: ]+)[: ]+([^; ]+)[; ]*/g, (m, k, v) => o[k] = v)

console.log(o)

DynamicObject.TryConvert(ConvertBinder, Object) Method (System , Be sure to use string and object as the key and value types. Otherwise, it will throw a RuntimeBinderException during the conversion. The  Is there a straightforward way of converting: string str = "a=1,b=2,c=3"; into: dynamic d = new { a = 1, b = 2, c = 3 }; I think I could probably write a function that splits the string and loops the results to create the dynamic object. I was just wondering if there was a more elegant way of doing this.

Please do some searching before asking. People are going to rate your question down now. But here's an answer anyway...

const str = "background #2b2b2b; color: #FFFFFF"
const obj = str.split('; ').reduce((acc, keyVal) => {
  const [key, val] = keyVal.split(' ')
  acc[key] = val
  return acc
}, {})

console.log(obj) // {background: "#2b2b2b", color:: "#FFFFFF"}

// if str was just 'background #2b2b2b;' it would include the ;
// {background: "#2b2b2b;"}

As someone mentioned your string is inconsistent so you'll need to fix the string format or add ways to handle edge cases.

Update: Perhaps a more flexible way would be to use RegExp. I'm not the best at writing RegExps so it could probably be improved.

// add acceptable characters in the brackets [ ]
const re = /([a-z-]+):\s?([()'"#a-z0-9]+);/gi

const str = 'background: #2b2b2b; color: #FFFFFF;background-url: url("test");'
const styles = {}

let next

while ((next = re.exec(str)) !== null) {
  const key = next[1]
  const value = next[2]
  // or const [ _, key, value ] = next

  styles[key] = value
}

console.log(styles)

/*
{
  background: '#2b2b2b',
  color: '#FFFFFF',
  'background-url': 'url("test")'
}
*/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

Using type dynamic, Dynamic objects in C# let us work with objects without compile time error checking in .NET. public Dog( string name, string type, int age). We can convert String to Object in java with assignment operator. Each class is internally a child class of Object class. So you can assign string to Object directly. You can also convert String to Class type object using Class.forName () method. Java String to Object Example. Let's see the simple code to convert String to Object in java.

You can convert

let styles = "background #2b2b2b; color: #FFFFFF";

into

stylesObj = {background: styles.split(";")[0].trim().split(" ")[1], 
                       color: styles.split(";")[1].trim().split(" ")[1]}

// {background: "#2b2b2b", color: "#FFFFFF"}

and you should get it in the form that you want.

EDIT

Added the .trim(), otherwise it does not work if the string has extra spaces.

Working with the Dynamic Type in C#, Convert input Json string to a dynamic object. dynamic input = JsonConvert.​DeserializeObject(myQueueItem);. // Create a dynamic output  I am storing a class object into a string using toString() method. Now, I want to convert the string into that class object. First, if I'm understanding your question, you want to store your object into a String and then later to be able to read it again and re-create the Object. Personally, when I need to do that I use ObjectOutputStream.

Convert a dynamic type to a concrete object in .NET C#, In it, you'll find recipes on asynchronous methods, dynamic objects, void AddProperty(ExpandoObject expando, string propertyName, object  dynamic dynamicDog = new Dog ("Fiffi", "Terrier", 3); Dog convertedDog = dynamicDog; Console.WriteLine (convertedDog.Name); We didn’t even have to use an explicit cast here. As long as the dynamic object can be implicitly cast to a concrete object then the above code will work. However, if we try to convert a Dog to an integer…:

C# Using Newtonsoft and dynamic ExpandoObject to convert one , Json NuGet package to your project, you can convert your object to a string with this single line of code: string strCust = JsonConvert. Ideal code for the Process: public static Boolean InsertSOjects(String sObjectApiName, String jSONSObject) { Map<String, Object> fieldMap = (Map<String, Object>)JSON.deserializeUntyped(jSONSObject);

Building C# objects dynamically with ExpandoObject – O'Reilly, The JValue structure supports importing JSON via the Parse() and Load() Once cast to dynamic I can then go ahead and access the object  We can use ExpandoObject to create an initial object to hold the Name and current Country of a person. dynamic expando = new ExpandoObject(); expando.Name = "Brian"; expando.Country = "USA"; Once we have added properties directly, we can also add properties to our object in a more dynamic fashion using the AddProperty method we have provided

Comments
  • doesnt seem like a valid CSS, but you can look for parser that can handle missing : stackoverflow.com/questions/3326494/…
  • This would be difficult to convert mainly because there doesn't seem to be a consistent pattern for separating keys and values. The key background is separated from the value #2b2b2b by a space, but the key color is separated from the value #FFFFFF by a colon and a space. If this was a typo and there is actually a colon after background then this would be doable if there's a guarantee that the string will always be valid css (i.e. the format will always be key1: value1; key2: value2; key3: value3)
  • Just for the sake of adding something to the boilerplate, you should handle the case where there is more than one space, like: border: 1px solid black (the current behavior will return "border: 1px"). Also, beware that this syntax may not be compatible in all browsers, so it's worth mentioning that. You may change const [key, val] to : const [key, ...val], then acc[key] = val to acc[key] = val.join(' ')
  • Maybe if @Benjamin Russel clears up if it is just a typo you can split on : , because at the moment the object is not converted completely right (Note the extra : in the objects color key color:: "#FFFFFF")
  • Good mentions +1. Yeah, he'll have to change the split('; ') to match whatever his input strings actually look like and maybe throw in a .trim
  • I think a more general/dynamic solution might be better for this case. Just imagine that the key (e.g. background) might change or that there are multiple values as mentioned above by @briosheje. Also this tends to get unreadable as you are chaining the string operations. Furthermore you are executing the same operation twice (styles.split(';'))
  • Ok, that is fair.