Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have attempted all require strict adherence to the JSON format.

Does anyone have any recommendations for a library that offers an option to parse this unconventional JSON format, or perhaps suggest a different approach such as utilizing regex instead?

Answer №1

Check out this CoffeeScript solution utilizing the underscore library. If you're not using underscore, you can easily swap _.foldl with a for loop.

 alterJsonStructure = (value) ->
        inQuotes = false
        correctQuotationMarks = (memo, nextCharacter) ->
            insertQuote =
                (inQuotes and not /[a-z0-9_"]/.test nextCharacter) or
                (!inQuotes and /[a-z_]/.test nextCharacter)
            inQuotes = (inQuotes != (insertQuote or nextCharacter == '"') )
            memo + (if insertQuote then '"' else '') + nextCharacter
        valueWithQuotes = _.foldl(value + '\n', correctQuotationMarks, "")
        JSON.parse(valueWithQuotes)

Alternatively, here's the same function but written in JavaScript:

function alterJsonStructure(value) {
  var correctQuotationMarks, inQuotes, valueWithQuotes;
  inQuotes = false;
  correctQuotationMarks = function(memo, nextCharacter) {
    var insertQuote;
    insertQuote = (inQuotes && !/[a-z0-9_"]/.test(nextCharacter)) || (!inQuotes && /[a-z_]/.test(nextCharacter));
    inQuotes = inQuotes !== (insertQuote || nextCharacter === '"');
    return memo + (insertQuote ? '"' : '') + nextCharacter;
  };
  valueWithQuotes = _.foldl(value + '\n', correctQuotationMarks, "");
  return JSON.parse(valueWithQuotes);
};

Answer №2

If the keys are not wrapped in quotes, it does not qualify as JSON.

You have two options: figure out how to do it on your own or seek help from someone who has already done it.

It is important to note that there is no concept of "non-strict json." JSON has only one version, and it adheres strictly to its format.

Answer №3

In my opinion, implementing a state pattern could be a helpful approach to inserting quotes into your text. The state pattern would work by analyzing characters one by one and keeping track of whether we are inside double quotes or if the double quotes are escaped with a backslash. By utilizing this method and remembering that variable names cannot begin with numbers, you can seamlessly add quotes as you stream the text, ensuring it is processed correctly.

Answer №4

One approach to parsing JSON is using the eval function:

var data = eval(jsonString)

It's important to exercise caution with using eval as it can execute code, so ensure you are aware of what data you are parsing.
Alternatively, there is a node module named jsonic that can parse non-strict JSON.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Vue to create multiple components and interact with Vuex state properties

I am currently learning Vue and using it with Vuex (without Webpack). However, I am facing some challenges while implementing a simple example and the documentation is not very clear to me. One issue I encountered is that I cannot access the Vuex st ...

Update overall font size to be 62% for a consistent look across the website

Recently, I developed a browser extension that adds an overlay button to the LinkedIn website. Everything was running smoothly until I discovered that LinkedIn uses a global font-size: 62,5% that completely messes up my design.. https://i.stack.imgur.com ...

Steps for utilizing a prepared statement

Is it recommended to use a prepared statement? I'm unsure how to implement it in my code. What modifications should I make? try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("\n Driver loaded"); Connection con ...

Setting the active class for a dynamic linkTo in EmberJS menu when directly accessed

For the past week, I've been attempting to get the active class functioning on these dynamic links: <li>{{#linkTo tag 'bw'}}Black and White{{/linkTo}}</li> <li>{{#linkTo tag 'instax'}}Instax{{/linkTo}}</li> ...

What is the reason for the index.html file not connecting to the local .css files and .js file?

I'm currently using node.js to send an .html file that includes the following tags: <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="description" content="This is my personal profile website" /> <link r ...

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

Determine the size of the JSON string

I am working with the following JSON string: var j = { "name": "John" }; alert(j.length); When I run this code, it alerts 'undefined'. How can I find the length of a JSON array object? Thank you. ...

Dealing with unescaped double quotes in values while using JSON_VALUE()

I'm currently facing an issue with a table in my database where the field JSONDetail stores JSON data. The problem arose when we encountered unescaped double quotes within one of the values in this field, likely due to migrating from a system that all ...

What steps do I need to take in order to implement a recursive function that keeps track of the history of local variables

Check out this cool function that takes a multi-dimensional array and converts it into a single-dimensional array using recursion. It's pretty nifty because it doesn't use any global variables, so everything is contained within the function itsel ...

Error has occurred: Unable to assign a value to an undefined property using axios

Within my Vue.js component, I am utilizing axios to fetch a JSON array consisting of `joke` objects: <template> <div id="show-jokes-all"> <h2>Showing all jokes</h2> <div v-for="joke in jokes"> ...

Error: Arrays need to be accessed using integer values, not strings - python

Struggling to access a JSON api and extract only the "genres" data, resulting in this error: Error: TypeError: list indices must be integers, not str Here's my code snippet: import urllib import json u = urllib.urlopen('http://api.tvmaze.com/ ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

Is there a way to retrieve the value of an HTML variable using Selenium?

Seeking assistance in determining the progress value of a video using Selenium. I understand that I need to utilize JavaScript executor, but have been unsuccessful in finding a solution so far. The element in question is: <div aria-label="scrub bar" a ...

What is the best way to trigger a Quasar dialog from an outside component?

Currently, I am working with Vue.js 2.x + Quasar 1.x using http-vue-loader (no build tools required). I have placed a q-dialog in a separate component named MyComponent. However, when I try to include it in a parent component like this: <my-component&g ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Access and retrieve real-time JavaScript variables directly from a website

Question: I am curious about the possibility of accessing JavaScript variables on a website from C#. Since the scripts are on the client side, is it possible to read their values live through C#? Any assistance or guidance on this matter would be greatly ...

The data in ag Grid does not display until all grid events have been completed

After setting the rowData in the onGridReady function, I noticed that the data does not display until all events are completed. I also attempted using the firstCellrendered event, but unfortunately, it did not resolve the issue. OnGridReady(){ this.r ...

Updating the value of a MongoDB item two days after its creation

I've been working on a NodeJS application that stores form data in a MongoDB database collection. My goal is to implement a function that can modify certain values of the object in the database collection 48 hours after the form data is initially save ...

Reassemble the separated string while skipping over every other element in the array created by splitting it

Currently, I am working on the following URL: demo.example.in/posts/0ewsd/13213 My goal is to extract the hostname (demo.example.in) and the path (posts/0ewsd/13213) from this URL. urlHost = 'demo.example.in/posts/0ewsd/13213'; let urlHostName ...