How to enforce quotes on property names on JSON .NET












1















I am using Json.NET to Parse some JSON I receive to an endpoint I have on my application.



I want the following JSON object to fail parsing since its property name does not have quotes on it:



{
foo: "bar"
}


JToken.Parse() says it is valid JSON. However, when I used an online parser I get the following error




Strings should be wrapped in double quotes.




Is there a way to make JSON .NET enforce this rule?










share|improve this question




















  • 1





    Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

    – dbc
    Nov 14 '18 at 16:08






  • 1





    The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

    – paddingtonMike
    Nov 14 '18 at 16:24






  • 1





    Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

    – dbc
    Nov 14 '18 at 16:59













  • That would be very useful, thanks.

    – paddingtonMike
    Nov 14 '18 at 17:04











  • Answer added, and updated.

    – dbc
    Nov 14 '18 at 18:30
















1















I am using Json.NET to Parse some JSON I receive to an endpoint I have on my application.



I want the following JSON object to fail parsing since its property name does not have quotes on it:



{
foo: "bar"
}


JToken.Parse() says it is valid JSON. However, when I used an online parser I get the following error




Strings should be wrapped in double quotes.




Is there a way to make JSON .NET enforce this rule?










share|improve this question




















  • 1





    Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

    – dbc
    Nov 14 '18 at 16:08






  • 1





    The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

    – paddingtonMike
    Nov 14 '18 at 16:24






  • 1





    Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

    – dbc
    Nov 14 '18 at 16:59













  • That would be very useful, thanks.

    – paddingtonMike
    Nov 14 '18 at 17:04











  • Answer added, and updated.

    – dbc
    Nov 14 '18 at 18:30














1












1








1








I am using Json.NET to Parse some JSON I receive to an endpoint I have on my application.



I want the following JSON object to fail parsing since its property name does not have quotes on it:



{
foo: "bar"
}


JToken.Parse() says it is valid JSON. However, when I used an online parser I get the following error




Strings should be wrapped in double quotes.




Is there a way to make JSON .NET enforce this rule?










share|improve this question
















I am using Json.NET to Parse some JSON I receive to an endpoint I have on my application.



I want the following JSON object to fail parsing since its property name does not have quotes on it:



{
foo: "bar"
}


JToken.Parse() says it is valid JSON. However, when I used an online parser I get the following error




Strings should be wrapped in double quotes.




Is there a way to make JSON .NET enforce this rule?







.net json json.net jsonparser






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 3:34









dbc

54.6k873127




54.6k873127










asked Nov 14 '18 at 15:59









paddingtonMikepaddingtonMike

55411025




55411025








  • 1





    Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

    – dbc
    Nov 14 '18 at 16:08






  • 1





    The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

    – paddingtonMike
    Nov 14 '18 at 16:24






  • 1





    Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

    – dbc
    Nov 14 '18 at 16:59













  • That would be very useful, thanks.

    – paddingtonMike
    Nov 14 '18 at 17:04











  • Answer added, and updated.

    – dbc
    Nov 14 '18 at 18:30














  • 1





    Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

    – dbc
    Nov 14 '18 at 16:08






  • 1





    The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

    – paddingtonMike
    Nov 14 '18 at 16:24






  • 1





    Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

    – dbc
    Nov 14 '18 at 16:59













  • That would be very useful, thanks.

    – paddingtonMike
    Nov 14 '18 at 17:04











  • Answer added, and updated.

    – dbc
    Nov 14 '18 at 18:30








1




1





Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

– dbc
Nov 14 '18 at 16:08





Related: Disable Support for Reading (Invalid JSON) Single Quote Strings.

– dbc
Nov 14 '18 at 16:08




1




1





The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

– paddingtonMike
Nov 14 '18 at 16:24





The problem with that answer is that it does not show an appropiate way of implementing the solution. I took a look at the JsonTextReader class from JSON .NET and I am not sure what I am supposed to do. I cannot believe that such a popular library like JSON .NET cannot support strict parsing.

– paddingtonMike
Nov 14 '18 at 16:24




1




1





Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

– dbc
Nov 14 '18 at 16:59







Also related: Unquoted json property name. That one was never answered but the comment states, It doesn't look that way. Shall I make that an answer, with some added details about how to fork JsonTextReader to do what you need?

– dbc
Nov 14 '18 at 16:59















That would be very useful, thanks.

– paddingtonMike
Nov 14 '18 at 17:04





That would be very useful, thanks.

– paddingtonMike
Nov 14 '18 at 17:04













Answer added, and updated.

– dbc
Nov 14 '18 at 18:30





Answer added, and updated.

– dbc
Nov 14 '18 at 18:30












1 Answer
1






active

oldest

votes


















1














Json.NET does not currently implement strict parsing of JSON property names.



Internally JToken.Parse() constructs a JsonTextReader to parse a JSON string, and it appears the ability of JsonTextReaderto parse unquoted property names cannot currently be disabled.



When iterating through a JSON file via JsonTextReader.Read(), the method JsonTextReader.ParseProperty() is used to parse property names:



Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty() 
Newtonsoft.Json.JsonTextReader.ParseProperty()
Newtonsoft.Json.JsonTextReader.ParseObject()
Newtonsoft.Json.JsonTextReader.Read()
Newtonsoft.Json.Linq.JContainer.ReadTokenFrom()


And, as seen from the current reference source, this method automatically handles properties that are double-quoted, single-quoted and unquoted:



private bool ParseProperty()
{
char firstChar = _chars[_charPos];
char quoteChar;

if (firstChar == '"' || firstChar == ''')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quoteChar);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '';
ShiftBufferIfNeeded();
ParseUnquotedProperty();
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}

// REMAINDER OMITTED


As you can see there is no option to configure the reader to throw an exception for non-double-quoted properties.



As a workaround, the current Json.NET license allows for copying and modification. Thus you should be able to create your own public class StricterJsonTextReader : JsonReader copied from JsonTextReader, and modify ParseProperty() as follows:



private bool ParseProperty()
{
char firstChar = _chars[_charPos];
char quoteChar;

if (firstChar == '"')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
ReadStringIntoBuffer(quoteChar);
}
else
{
// JsonReaderException.Create() is an internal static method,
// so you will need to replace this with some extension method
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}


However, this may not be an entirely easy job, as JsonTextReader makes extensive use of utilities from the Src/Newtonsoft.Json/Utilities directory. You should budget a couple of days for making a minimal copy of the necessary utilities.



Alternatively, you could fork your own version of Json.NET, build it yourself, and use it instead of the official version. Either way, be sure to fork the source from the version you want to use:



Select the correct version



As an alternative to creating your own parser, you could preprocess your JSON with JsonReaderWriterFactory.CreateJsonReader() to ensure strict compliance with the JSON standard:



public static class JsonExtensions
{
public static JToken StrictParse(string json)
{
try
{
// Throw an exception if the json string is not in strict compliance with the JSON standard
// by tokenizing it with the JSON reader used by DataContractJsonSerializer:
using (var stream = GenerateStreamFromString(json))
using (var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(stream, System.Xml.XmlDictionaryReaderQuotas.Max))
{
while (reader.Read())
{
}
}
}
catch (Exception ex)
{
// Wrap the XmlException in a JsonReaderException
throw new JsonReaderException("Invalid JSON", ex);
}
// Then actually parse with Json.NET
return JToken.Parse(json);
}

static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
}
}


(You will need to add a reference to the appropriate .Net assembly for your framework.)



The performance will be worse since you will effectively be parsing your JSON twice, but the implementation effort is trivial.



Oddly enough, I was unable to use JavaScriptSerializer to check for strict JSON compliance because it also accepts unquoted property names!



// The following does not throw an exception:
new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject("{foo : 'bar'}")


Related links:




  • Disable Support for Reading (Invalid JSON) Single Quote Strings for which the answer is to create your own JsonReader.


  • Unquoted json property name which has no answer.



  • Issue #646: Support "strict mode" for RFC7159 parsing which was closed by JamesNK. The discussion thread enumerates various ways that JsonTextReader extends the JSON standard, as well as some reasons as to why Newtonsoft has not yet implemented a strict parser.



    Even though the issue was closed, you could certainly add a comment requesting a strict parsing option. Certainly it seems like something they ought to provide.








share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304218%2fhow-to-enforce-quotes-on-property-names-on-json-net%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Json.NET does not currently implement strict parsing of JSON property names.



    Internally JToken.Parse() constructs a JsonTextReader to parse a JSON string, and it appears the ability of JsonTextReaderto parse unquoted property names cannot currently be disabled.



    When iterating through a JSON file via JsonTextReader.Read(), the method JsonTextReader.ParseProperty() is used to parse property names:



    Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty() 
    Newtonsoft.Json.JsonTextReader.ParseProperty()
    Newtonsoft.Json.JsonTextReader.ParseObject()
    Newtonsoft.Json.JsonTextReader.Read()
    Newtonsoft.Json.Linq.JContainer.ReadTokenFrom()


    And, as seen from the current reference source, this method automatically handles properties that are double-quoted, single-quoted and unquoted:



    private bool ParseProperty()
    {
    char firstChar = _chars[_charPos];
    char quoteChar;

    if (firstChar == '"' || firstChar == ''')
    {
    _charPos++;
    quoteChar = firstChar;
    ShiftBufferIfNeeded();
    ReadStringIntoBuffer(quoteChar);
    }
    else if (ValidIdentifierChar(firstChar))
    {
    quoteChar = '';
    ShiftBufferIfNeeded();
    ParseUnquotedProperty();
    }
    else
    {
    throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
    }

    // REMAINDER OMITTED


    As you can see there is no option to configure the reader to throw an exception for non-double-quoted properties.



    As a workaround, the current Json.NET license allows for copying and modification. Thus you should be able to create your own public class StricterJsonTextReader : JsonReader copied from JsonTextReader, and modify ParseProperty() as follows:



    private bool ParseProperty()
    {
    char firstChar = _chars[_charPos];
    char quoteChar;

    if (firstChar == '"')
    {
    _charPos++;
    quoteChar = firstChar;
    ShiftBufferIfNeeded();
    ReadStringIntoBuffer(quoteChar);
    }
    else
    {
    // JsonReaderException.Create() is an internal static method,
    // so you will need to replace this with some extension method
    throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
    }


    However, this may not be an entirely easy job, as JsonTextReader makes extensive use of utilities from the Src/Newtonsoft.Json/Utilities directory. You should budget a couple of days for making a minimal copy of the necessary utilities.



    Alternatively, you could fork your own version of Json.NET, build it yourself, and use it instead of the official version. Either way, be sure to fork the source from the version you want to use:



    Select the correct version



    As an alternative to creating your own parser, you could preprocess your JSON with JsonReaderWriterFactory.CreateJsonReader() to ensure strict compliance with the JSON standard:



    public static class JsonExtensions
    {
    public static JToken StrictParse(string json)
    {
    try
    {
    // Throw an exception if the json string is not in strict compliance with the JSON standard
    // by tokenizing it with the JSON reader used by DataContractJsonSerializer:
    using (var stream = GenerateStreamFromString(json))
    using (var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(stream, System.Xml.XmlDictionaryReaderQuotas.Max))
    {
    while (reader.Read())
    {
    }
    }
    }
    catch (Exception ex)
    {
    // Wrap the XmlException in a JsonReaderException
    throw new JsonReaderException("Invalid JSON", ex);
    }
    // Then actually parse with Json.NET
    return JToken.Parse(json);
    }

    static MemoryStream GenerateStreamFromString(string value)
    {
    return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
    }
    }


    (You will need to add a reference to the appropriate .Net assembly for your framework.)



    The performance will be worse since you will effectively be parsing your JSON twice, but the implementation effort is trivial.



    Oddly enough, I was unable to use JavaScriptSerializer to check for strict JSON compliance because it also accepts unquoted property names!



    // The following does not throw an exception:
    new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject("{foo : 'bar'}")


    Related links:




    • Disable Support for Reading (Invalid JSON) Single Quote Strings for which the answer is to create your own JsonReader.


    • Unquoted json property name which has no answer.



    • Issue #646: Support "strict mode" for RFC7159 parsing which was closed by JamesNK. The discussion thread enumerates various ways that JsonTextReader extends the JSON standard, as well as some reasons as to why Newtonsoft has not yet implemented a strict parser.



      Even though the issue was closed, you could certainly add a comment requesting a strict parsing option. Certainly it seems like something they ought to provide.








    share|improve this answer






























      1














      Json.NET does not currently implement strict parsing of JSON property names.



      Internally JToken.Parse() constructs a JsonTextReader to parse a JSON string, and it appears the ability of JsonTextReaderto parse unquoted property names cannot currently be disabled.



      When iterating through a JSON file via JsonTextReader.Read(), the method JsonTextReader.ParseProperty() is used to parse property names:



      Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty() 
      Newtonsoft.Json.JsonTextReader.ParseProperty()
      Newtonsoft.Json.JsonTextReader.ParseObject()
      Newtonsoft.Json.JsonTextReader.Read()
      Newtonsoft.Json.Linq.JContainer.ReadTokenFrom()


      And, as seen from the current reference source, this method automatically handles properties that are double-quoted, single-quoted and unquoted:



      private bool ParseProperty()
      {
      char firstChar = _chars[_charPos];
      char quoteChar;

      if (firstChar == '"' || firstChar == ''')
      {
      _charPos++;
      quoteChar = firstChar;
      ShiftBufferIfNeeded();
      ReadStringIntoBuffer(quoteChar);
      }
      else if (ValidIdentifierChar(firstChar))
      {
      quoteChar = '';
      ShiftBufferIfNeeded();
      ParseUnquotedProperty();
      }
      else
      {
      throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
      }

      // REMAINDER OMITTED


      As you can see there is no option to configure the reader to throw an exception for non-double-quoted properties.



      As a workaround, the current Json.NET license allows for copying and modification. Thus you should be able to create your own public class StricterJsonTextReader : JsonReader copied from JsonTextReader, and modify ParseProperty() as follows:



      private bool ParseProperty()
      {
      char firstChar = _chars[_charPos];
      char quoteChar;

      if (firstChar == '"')
      {
      _charPos++;
      quoteChar = firstChar;
      ShiftBufferIfNeeded();
      ReadStringIntoBuffer(quoteChar);
      }
      else
      {
      // JsonReaderException.Create() is an internal static method,
      // so you will need to replace this with some extension method
      throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
      }


      However, this may not be an entirely easy job, as JsonTextReader makes extensive use of utilities from the Src/Newtonsoft.Json/Utilities directory. You should budget a couple of days for making a minimal copy of the necessary utilities.



      Alternatively, you could fork your own version of Json.NET, build it yourself, and use it instead of the official version. Either way, be sure to fork the source from the version you want to use:



      Select the correct version



      As an alternative to creating your own parser, you could preprocess your JSON with JsonReaderWriterFactory.CreateJsonReader() to ensure strict compliance with the JSON standard:



      public static class JsonExtensions
      {
      public static JToken StrictParse(string json)
      {
      try
      {
      // Throw an exception if the json string is not in strict compliance with the JSON standard
      // by tokenizing it with the JSON reader used by DataContractJsonSerializer:
      using (var stream = GenerateStreamFromString(json))
      using (var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(stream, System.Xml.XmlDictionaryReaderQuotas.Max))
      {
      while (reader.Read())
      {
      }
      }
      }
      catch (Exception ex)
      {
      // Wrap the XmlException in a JsonReaderException
      throw new JsonReaderException("Invalid JSON", ex);
      }
      // Then actually parse with Json.NET
      return JToken.Parse(json);
      }

      static MemoryStream GenerateStreamFromString(string value)
      {
      return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
      }
      }


      (You will need to add a reference to the appropriate .Net assembly for your framework.)



      The performance will be worse since you will effectively be parsing your JSON twice, but the implementation effort is trivial.



      Oddly enough, I was unable to use JavaScriptSerializer to check for strict JSON compliance because it also accepts unquoted property names!



      // The following does not throw an exception:
      new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject("{foo : 'bar'}")


      Related links:




      • Disable Support for Reading (Invalid JSON) Single Quote Strings for which the answer is to create your own JsonReader.


      • Unquoted json property name which has no answer.



      • Issue #646: Support "strict mode" for RFC7159 parsing which was closed by JamesNK. The discussion thread enumerates various ways that JsonTextReader extends the JSON standard, as well as some reasons as to why Newtonsoft has not yet implemented a strict parser.



        Even though the issue was closed, you could certainly add a comment requesting a strict parsing option. Certainly it seems like something they ought to provide.








      share|improve this answer




























        1












        1








        1







        Json.NET does not currently implement strict parsing of JSON property names.



        Internally JToken.Parse() constructs a JsonTextReader to parse a JSON string, and it appears the ability of JsonTextReaderto parse unquoted property names cannot currently be disabled.



        When iterating through a JSON file via JsonTextReader.Read(), the method JsonTextReader.ParseProperty() is used to parse property names:



        Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty() 
        Newtonsoft.Json.JsonTextReader.ParseProperty()
        Newtonsoft.Json.JsonTextReader.ParseObject()
        Newtonsoft.Json.JsonTextReader.Read()
        Newtonsoft.Json.Linq.JContainer.ReadTokenFrom()


        And, as seen from the current reference source, this method automatically handles properties that are double-quoted, single-quoted and unquoted:



        private bool ParseProperty()
        {
        char firstChar = _chars[_charPos];
        char quoteChar;

        if (firstChar == '"' || firstChar == ''')
        {
        _charPos++;
        quoteChar = firstChar;
        ShiftBufferIfNeeded();
        ReadStringIntoBuffer(quoteChar);
        }
        else if (ValidIdentifierChar(firstChar))
        {
        quoteChar = '';
        ShiftBufferIfNeeded();
        ParseUnquotedProperty();
        }
        else
        {
        throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
        }

        // REMAINDER OMITTED


        As you can see there is no option to configure the reader to throw an exception for non-double-quoted properties.



        As a workaround, the current Json.NET license allows for copying and modification. Thus you should be able to create your own public class StricterJsonTextReader : JsonReader copied from JsonTextReader, and modify ParseProperty() as follows:



        private bool ParseProperty()
        {
        char firstChar = _chars[_charPos];
        char quoteChar;

        if (firstChar == '"')
        {
        _charPos++;
        quoteChar = firstChar;
        ShiftBufferIfNeeded();
        ReadStringIntoBuffer(quoteChar);
        }
        else
        {
        // JsonReaderException.Create() is an internal static method,
        // so you will need to replace this with some extension method
        throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
        }


        However, this may not be an entirely easy job, as JsonTextReader makes extensive use of utilities from the Src/Newtonsoft.Json/Utilities directory. You should budget a couple of days for making a minimal copy of the necessary utilities.



        Alternatively, you could fork your own version of Json.NET, build it yourself, and use it instead of the official version. Either way, be sure to fork the source from the version you want to use:



        Select the correct version



        As an alternative to creating your own parser, you could preprocess your JSON with JsonReaderWriterFactory.CreateJsonReader() to ensure strict compliance with the JSON standard:



        public static class JsonExtensions
        {
        public static JToken StrictParse(string json)
        {
        try
        {
        // Throw an exception if the json string is not in strict compliance with the JSON standard
        // by tokenizing it with the JSON reader used by DataContractJsonSerializer:
        using (var stream = GenerateStreamFromString(json))
        using (var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(stream, System.Xml.XmlDictionaryReaderQuotas.Max))
        {
        while (reader.Read())
        {
        }
        }
        }
        catch (Exception ex)
        {
        // Wrap the XmlException in a JsonReaderException
        throw new JsonReaderException("Invalid JSON", ex);
        }
        // Then actually parse with Json.NET
        return JToken.Parse(json);
        }

        static MemoryStream GenerateStreamFromString(string value)
        {
        return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }
        }


        (You will need to add a reference to the appropriate .Net assembly for your framework.)



        The performance will be worse since you will effectively be parsing your JSON twice, but the implementation effort is trivial.



        Oddly enough, I was unable to use JavaScriptSerializer to check for strict JSON compliance because it also accepts unquoted property names!



        // The following does not throw an exception:
        new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject("{foo : 'bar'}")


        Related links:




        • Disable Support for Reading (Invalid JSON) Single Quote Strings for which the answer is to create your own JsonReader.


        • Unquoted json property name which has no answer.



        • Issue #646: Support "strict mode" for RFC7159 parsing which was closed by JamesNK. The discussion thread enumerates various ways that JsonTextReader extends the JSON standard, as well as some reasons as to why Newtonsoft has not yet implemented a strict parser.



          Even though the issue was closed, you could certainly add a comment requesting a strict parsing option. Certainly it seems like something they ought to provide.








        share|improve this answer















        Json.NET does not currently implement strict parsing of JSON property names.



        Internally JToken.Parse() constructs a JsonTextReader to parse a JSON string, and it appears the ability of JsonTextReaderto parse unquoted property names cannot currently be disabled.



        When iterating through a JSON file via JsonTextReader.Read(), the method JsonTextReader.ParseProperty() is used to parse property names:



        Newtonsoft.Json.JsonTextReader.ParseUnquotedProperty() 
        Newtonsoft.Json.JsonTextReader.ParseProperty()
        Newtonsoft.Json.JsonTextReader.ParseObject()
        Newtonsoft.Json.JsonTextReader.Read()
        Newtonsoft.Json.Linq.JContainer.ReadTokenFrom()


        And, as seen from the current reference source, this method automatically handles properties that are double-quoted, single-quoted and unquoted:



        private bool ParseProperty()
        {
        char firstChar = _chars[_charPos];
        char quoteChar;

        if (firstChar == '"' || firstChar == ''')
        {
        _charPos++;
        quoteChar = firstChar;
        ShiftBufferIfNeeded();
        ReadStringIntoBuffer(quoteChar);
        }
        else if (ValidIdentifierChar(firstChar))
        {
        quoteChar = '';
        ShiftBufferIfNeeded();
        ParseUnquotedProperty();
        }
        else
        {
        throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
        }

        // REMAINDER OMITTED


        As you can see there is no option to configure the reader to throw an exception for non-double-quoted properties.



        As a workaround, the current Json.NET license allows for copying and modification. Thus you should be able to create your own public class StricterJsonTextReader : JsonReader copied from JsonTextReader, and modify ParseProperty() as follows:



        private bool ParseProperty()
        {
        char firstChar = _chars[_charPos];
        char quoteChar;

        if (firstChar == '"')
        {
        _charPos++;
        quoteChar = firstChar;
        ShiftBufferIfNeeded();
        ReadStringIntoBuffer(quoteChar);
        }
        else
        {
        // JsonReaderException.Create() is an internal static method,
        // so you will need to replace this with some extension method
        throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
        }


        However, this may not be an entirely easy job, as JsonTextReader makes extensive use of utilities from the Src/Newtonsoft.Json/Utilities directory. You should budget a couple of days for making a minimal copy of the necessary utilities.



        Alternatively, you could fork your own version of Json.NET, build it yourself, and use it instead of the official version. Either way, be sure to fork the source from the version you want to use:



        Select the correct version



        As an alternative to creating your own parser, you could preprocess your JSON with JsonReaderWriterFactory.CreateJsonReader() to ensure strict compliance with the JSON standard:



        public static class JsonExtensions
        {
        public static JToken StrictParse(string json)
        {
        try
        {
        // Throw an exception if the json string is not in strict compliance with the JSON standard
        // by tokenizing it with the JSON reader used by DataContractJsonSerializer:
        using (var stream = GenerateStreamFromString(json))
        using (var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(stream, System.Xml.XmlDictionaryReaderQuotas.Max))
        {
        while (reader.Read())
        {
        }
        }
        }
        catch (Exception ex)
        {
        // Wrap the XmlException in a JsonReaderException
        throw new JsonReaderException("Invalid JSON", ex);
        }
        // Then actually parse with Json.NET
        return JToken.Parse(json);
        }

        static MemoryStream GenerateStreamFromString(string value)
        {
        return new MemoryStream(Encoding.UTF8.GetBytes(value ?? ""));
        }
        }


        (You will need to add a reference to the appropriate .Net assembly for your framework.)



        The performance will be worse since you will effectively be parsing your JSON twice, but the implementation effort is trivial.



        Oddly enough, I was unable to use JavaScriptSerializer to check for strict JSON compliance because it also accepts unquoted property names!



        // The following does not throw an exception:
        new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject("{foo : 'bar'}")


        Related links:




        • Disable Support for Reading (Invalid JSON) Single Quote Strings for which the answer is to create your own JsonReader.


        • Unquoted json property name which has no answer.



        • Issue #646: Support "strict mode" for RFC7159 parsing which was closed by JamesNK. The discussion thread enumerates various ways that JsonTextReader extends the JSON standard, as well as some reasons as to why Newtonsoft has not yet implemented a strict parser.



          Even though the issue was closed, you could certainly add a comment requesting a strict parsing option. Certainly it seems like something they ought to provide.









        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 18:26

























        answered Nov 14 '18 at 17:36









        dbcdbc

        54.6k873127




        54.6k873127
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304218%2fhow-to-enforce-quotes-on-property-names-on-json-net%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            The Sandy Post

            Danny Elfman

            Pages that link to "Head v. Amoskeag Manufacturing Co."