Deserializing malformed json string

I'm trying to use JsonConvert to deserialize a string into an object, but I'm getting the exception:

Unexpected character encountered while parsing value: s. Path 'type.id', line 1, position 12.

This is happening because the input string is not a properly formed json string, I understand that. However, the problem is that the string will never be a properly formatted json string and I cannot change that, but nonetheless, I still need to deserialize it to an object.

The string:

"{type: {id: schoolType1516,req: true,edit: yes},name: {id: schoolName1516,req: true,edit: yes}}"

How can I convert this string to properly formatted json string so it can be deserialized to an object using JsonConvert?

-------------Problems Reply------------

I'd use Regex.Replace, like this:

// Exchange all words with words surrounded by `"`
// ((\\w+\\s+)*\\w+) becomes ((\w+\s+)*\w+), ie all words with possible spaces
var match = "((\\w+\\s+)*\\w+)";
// \"$1\" becomes "$1" which is the sequence for replace the first group (ie the one
// we caught above) with the same group but with extra "
var replacement = "\"$1\"";
var correctJSON = Regex.Replace(faultyJSON, match, replacement);
// Parse it.
var obj = ...

If feels good to use regex though, https://xkcd.com/208/ :)

{"type": {"id": "schoolType1516","req": true,"edit": "yes"},"name": {"id": "schoolName1516","req": true,"edit": "yes"}}

You can use http://jsonformatter.curiousconcept.com/ to see what is wrong.

Strings and property names should be embraced with ' or ""

If you can't go back to your datasource and fix it there, you can try to fix your JSON string.

If it stays this simple, like in your sample you can select every word and wrap it in quotation marks:

//we only need every match once
var matches = Regex.Matches(source, @"\w+")
.OfType<Match>()
.Select (m => m.Groups[0].Value)
.Distinct();

foreach (var match in matches)
{
source = source.Replace(match, String.Format("\"{0}\"", match));
}

JObject obj = JObject.Parse(source);

Example: http://share.linqpad.net/sartkg.linq

Edit: fixed single quotes to double quotes.

Category:c# Views:8 Time:2019-01-29
Tags: json json.net

Related post

  • Parsing a malformed jSon string 2011-09-14

    I'm using a Java Json library to convert an incoming string into a json one. The lib is json-lib. The problem is that I can't modify the source so, sometimes I can get some malformed jSon strings especially this kind of key/value strings : "key":"a q

  • malformed JSON string, neither array, object, number, string or atom 2011-11-22

    I have trouble parsing a json object with perl and I don't know if the issue is coming from the json or my script. Here is the json: test.json { "count":3, "entries": [ { "id":85, "application":AuditExampleLogin1, "user":admin, "time":"2011-11-22T10:

  • Is this a bug? Decimal property not getting deserialized from JSON string (.NET MVC) 2012-03-28

    I have the following .Net class: public class Product { public int ID {get;set;} public String Name {get;set;} public Decimal Price {get;set;} } And an action in my controller: [HttpPost] public ActionResult AddProduct(Product product) { // product.P

  • Can a malformed JSON string be parsed successfully? 2011-02-28

    Here's a sample string: String s = "{\"source\": \"another \"quote inside\" text\"}"; What's the best way to parse this? I've already tried 4 parsers: json-lib, json-simple, gson, and Grails built-in JSON parser. I'm using Java and I want to know if

  • Can I control what subtype to use when deserializing a JSON string? 2010-07-25

    I'm working with Facebook API and it's search method returns a JSON response like this: { "data": [ { "id": "1", "message": "Heck of a babysitter...", "name": "Baby eating a watermelon", "type": "video" }, { "id": "2", "message": "Great Produce Deals

  • How to convert a JSON string to an object? 2010-06-10

    How can I convert a JSON string to an object in JavaScript? Is there a method that does this? Something like: var x = "{ id: 5, name: 'hello' }"; var y = /*something*/(x); alert(y.id + " " + y.name); --------------Solutions------------- As per the co

  • Deserializing JSON string to Object with json.net 2011-02-18

    I'm building a small application that pulls statistics from an API I have no control over. The JSON string looks like this: { "weapons": [ { "aek": { "name":"AEK-971 Vintovka", "kills":47, "shots_fired":5406, "shots_hit":858 }, "xm8": { "name":"XM8 P

  • perl: Uncaught exception: malformed UTF-8 character in JSON string 2011-08-01

    Related to this question and this answer (to another question) I am still unable to process UTF-8 with JSON. I have tried to make sure all the required voodoo is invoked based on recommendations from the very best experts, and as far as I can see the

  • Deserializing Json String containing interfaces not working in Java using Gson 2.3.1 2018-01-11

    I am trying to deserialize a json string which contains interfaces and hashmaps which has interface type and lists containing interface type into a java object using Gson. But I am getting java.lang.RuntimeException: Unable to invoke no-args construc

  • Deserializing twitter stream json string F#, how to define 'null' as a proper value? 2010-09-25

    I leave the below in case anybody wants the record types, but my question can be asked as following. Suppose one needs to write to a file a record type that can be null, what is the best way to achieve that, considering the below yields: "The type 'B

  • 2D JSON String Array Deserialized into JavaScript objects 2011-05-27

    Hi I have a JSON string that looks like this: {"2000":["1", "2", "3"],"2001":["1", "2", "3"],"2002":["1", "2", "3"]} The string above comes from the "backend" and my JavaScript function receives the JSON string as a parameter, which is called backend

  • Deserializing json string into an object - Silverlight 2012-04-11

    I've spent a good while this afternoon trying to implement the deserialization of JSON within a string, at first I was using DataContractJsonSerializer as my environment is Silverlight however it does not appear to support using a Dictionary out of t

  • Is there a built in way in .Net AJAX to manually serialize an object to a JSON string? 2008-08-29

    I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <System.Web.Services.WebMethod()> and <System

  • How to create JSON string in C# 2009-06-29

    I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the JSON string and them format your response as JSON? --------------Solutions----

  • How to decode HTML encoded character embedded in a json string 2009-07-09

    I've a little question about decoding special characters from a JSon result (in my case, \x27 but it could be any valid html encoded character). If the result doesn't contains any escaped characters, it works well but if not, I get a Unrecognized esc

  • json_decode on retrieved json string from mysql does not work 2009-10-28

    I have a string json that gives the following var dump: "[[{"TransactionID":"00416","OrderID":"000926","TransactionOrderItemID":"001123","LastUpdate":"2009-10-28 13:03:31","CustomerID":"184","Company_name":"Test123","Invoiced":"0","SubItemsCount":"2"

  • What is the simplest C# function to parse a JSON string into an object? 2010-05-18

    What is the simplest C# function to parse a JSON string into a object and display it (C# XAML WPF)? (for example object with 2 arrays - arrA and arrB) --------------Solutions------------- DataContractJsonSerializer serializer = new DataContractJsonSe

  • ie is not understanding 'false' from a JSON string? 2010-06-24

    I have some php that checks if a user is logged in and returns false, this is then passed via ajax to the browser to let the user know he needs to log in. Works perfect in FF and the alert returns 'true' but in IE, it returns 'null' no matter what I

  • Gson and the argonauts - problem converting javascript array, to json string, to java pojo using gson. Trying to get my structures correct 2010-09-07

    Here is my json string, that I am acessing in java: json = [ {"id":"123456","Data":"skill2","dmlcrud":false}, {"id":"123456","Data":"skill3","dmlcrud":true}, {"id":"123456","Data":"skill14","dmlcrud":true}, {"id":"123321","Data":"skill1","dmlcrud":fa

  • What is the easiest way to parse json using gson when the element to parse is an element of a json string? 2010-09-22

    I am using gson to parse json into java beans. For the API I am using, a large number of the json results include the result as the first property of a json object. The "gson way" seems to be to create an equivalent wrapper java object, which has one

  • Deserializing a JSON array of mixed types 2010-10-11

    I'm having trouble deserializing a JSON array of mixed types using the DataContractJsonSerializer class. I've spent a bunch of time looking for a solution to no avail, so I thought I'd go ahead and ask here. Basically, I am getting a JSON string like

  • Deserialization JSON string with JSON.NET 2010-11-13

    I am helpless, I need deserialize JSON string in this format to class. JSON string: {"newNickInfo":{"2775040":{"idUser":2775040,"nick":"minci88","sefNick":"minci88","sex":2,"photon":"http:\/\/213.215.107.125\/fotky\/277\/50\/n_2775040.jpg?v=4","photo

  • How can you stream results as json string downloads? 2011-01-12

    I'm interested in presenting results faster in my mobile app. Is it possible to stream results out as the string downloads? I'm thinking about implementing an IObservable to push out the results as they are downloaded, but I don't know what algorithm

  • Accessing Facebook servers with cross-domain JSONP and malformed JSON answer 2011-01-21

    I am trying to access facebook autocomplete service via a cross-domain scripting. replace id with your personal facebook user id, in the previous url. Please note that Facebook is returning a malformed JSON answer with an infinite loop for(;;); inser

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.164 (s). 11 q(s)