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

Implementing useState to toggle the checked value of a checkbox in React

When passing a list of checkbox fields with attributes to my component, I want to update the checked attribute based on user selection. However, all I have managed to do so far is double the check value in an array. How can I modify this specific key with ...

The Ajax post function successfully executes on the first attempt, but on subsequent tries it does

My goal is to send data from a forum asynchronously to a PHP page and display the response in a specific ID without refreshing the page. The first time I submit, everything works perfectly. The text is successfully sent to append.php and the new list of i ...

The interconnectivity between ngAfterViewInit in Angular's LifeCycle and observables

enable.service.ts @Injectable({ providedIn: 'root' }) export class EnableService { isEnabled$ = from(this.client.init()).pipe( switchMap(() => this.client.getEnabled()), map(([enabled, isAdmin]) => ({enabled: true, isAdmin: fals ...

Mapping an array of dictionaries containing key-value pairs to a specific class using a string identifier

I am trying to work with an Array of objects that are retrieved from a string. The information is received in an encrypted form through an API call, and upon decryption, it takes the form of a JSON structure presented below: { "request_id”:”abcds ...

What could be the reason for Selenium Webdriver failing to maximize the Chrome browser on a remote

My tests are running successfully on my local machine, but when I try to run them on the remote machine with Chrome not maximized, the driver is unable to locate the elements on the screen which leads to test failures. Despite trying all recommended soluti ...

Adjust the height of a UITextView to accommodate the entire content within a JSON string on iOS7

I have a UILabel inside my TableView Cell that is connected to a JSON String ("body") which I am parsing using AFNetworking. The text in this string varies for each post and I want the label to adjust its height based on the content of the string so that a ...

"Troubleshooting Error: When accessing a property in AngularJS,

My goal is to retrieve a date value. However, I encounter an error message saying 'Cannot read property 'NTLI' of undefined' whenever the checkbox is unchecked and the date picker is invisible. Strangely enough, everything works fine wh ...

Implement two different styles within an element's style properties

Welcome everyone, I have a question regarding adding marquee effects to a table row along with highlighting it. Is it possible to include moving text from left to right in the same active row? For example, let's say that the current time is 12:45 AM. ...

Manipulating the content of a specific row's table cells with a text box in jQuery Datatables

I am working with a jQuery datatable that consists of only one column. Every time a row is selected, a panel opens with a text box that automatically populates with the name of the selected td. I am trying to figure out how to edit the name of the selected ...

Necessary workaround needed for HTML time limit

Our HTML page has been designed to automatically timeout after 10 minutes of inactivity. This functionality is achieved through the following code: function CheckExpire() { $.ajax({ type:'GET', url:self.location.pathname+"?ch ...

Guidelines on centering an AJAX spinning animation within a parent div

Below is the basic structure of an HTML document for a webpage. <div class="grand-parent"> <div class="header">Heading</div> <div class="parent-div"> <div class="child-div-1"></div> ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

Proper techniques for testing an AngularJS Controller Function

Recently, we integrated jasmine tests into our AngularJS project and I have a query: We are looking to write tests for this controller function: $scope.deleteClick = function () { $scope.processing = true; peopleNotesSrv.deleteNote($scope ...

Trouble with fetching data from Swift/Firebase in the exact order it was entered?

Encountering issues with fetching data from Firebase in the exact order it was entered. I've experimented with different methods, including .valueAdded and .value, but haven't been successful in maintaining the original order. Could it be that my ...

I'm puzzled as to why a div tag suddenly becomes invisible when I attempt to link it with a v-for directive in my code

I am facing an issue with the div tag assigned to the log class. My objective is to populate the text using data retrieved from the API response. However, when I attempt to include the v-for directive, the entire div mysteriously disappears from the brow ...

"Undefined Step definitions in Cucumber for Java: How to Fix the

I've included the login steps in the Login class. However, when I execute the scenario from the Login.feature file, I continue to encounter undefined steps error. Login class package stepDefinitions; import io.cucumber.java.en.And; import io.cucumbe ...

Locate and filter elements by using the react-testing-library's getAll method

On my page, I have a collection of unique checkbox elements that are custom-designed. Each individual checkbox has the following structure: <div className="checkbox" role="checkbox" onClick={onClick} onKeyPress={onKeyPress} aria-checked={getS ...

Create a form in a React component that allows the user to input information

My challenge is to create a functionality where each time the add button is clicked, it should dynamically add an input field that I can save. It's similar to this example, but with inputs instead. The complexity arises from the fact that the inputs a ...

Guide to create a sliding menu transition from the viewport to the header

I am just starting to learn jQuery and I want to create a menu similar to the one on this website Specifically, I would like the menu to slide down from the viewport to the header, as shown in the template in the link. I have searched through the jQuery ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...