Struggling with handling white spaces during the transfer of JSON data to Python

As a high school math teacher, I am venturing into the world of programming to enhance my skills. Please bear with me if some of my terminology is not quite accurate.

Currently, I am facing an issue with transferring CSV data collected from users to a SQLite database using Python.

Everything seems to be functioning smoothly except when a value contains a space.

For instance, part of my JavaScript object looks like this:

Firstname: "Bruce"
Grade: ""
Lastname: "Wayne Jr"
Nickname: ""

After employing JSON.stringify, it becomes:

{"Firstname":"Bruce","Lastname":"Wayne Jr","Nickname":"","Grade":""}

This JSON data is then sent to Python via a form using the following code:

data = request.form.get("data")
print(data)
data2 = json.loads(data)
print(data2)

However, I am encountering multiple error messages, culminating in:

json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 250 (char 249)
. The log from the initial print statement displays:

[{"Firstname":"Jason","Lastname":"Bourne","Nickname":"","Grade":"10"},
 {"Firstname":"Steve","Lastname":"McGarret","Nickname":"5-0","Grade":""},
 {"Firstname":"Danny","Lastname":"Williams","Nickname":"Dano","Grade":"12"},
 {"Firstname":"Bruce","Lastname":"Wayne

The issue appears to arise from the space in "Wayne Jr".

I utilized the information found here as the foundation for my efforts:
https://bl.ocks.org/HarryStevens/0ce529b9b5e4ea17f8db25324423818f

I suspect that the JavaScript function below is responsible for processing user input:

function changeDataFromField(cb){
   var arr = [];
   $('#enter-data-field').val().replace( /\n/g, "^^^xyz" ).split( "^^^xyz" ).forEach(function(d){
     arr.push(d.replace( /\t/g, "^^^xyz" ).split( "^^^xyz" ))
   });
   cb(csvToJson(arr));
 }

Based on feedback, I should clarify that I am utilizing a POST request and not AJAX.

Users have two options for input: a text box for pasting CSV data and a file upload feature. Below is more of the accompanying JavaScript:

// Implement HTML5 File API for CSV parsing
  function changeDataFromUpload(evt, cb){
    if (!browserSupportFileUpload()) {
      console.error("The File APIs are not fully supported in this browser!");
    } else {
      var data = null;
      var file = evt.target.files[0];
      var fileName = file.name;
      $("#filename").html(fileName);

      if (file !== "") {
        var reader = new FileReader();

        reader.onload = function(event) {
          var csvData = event.target.result;
          var parsed = Papa.parse(csvData);
          cb(csvToJson(parsed.data));
        };
        reader.onerror = function() {
          console.error("Unable to read " + file.fileName);
        };
      }

      reader.readAsText(file);
      $("#update-data-from-file")[0].value = "";
    }
  }

  // Check for browser support of HTML5 File API
  function browserSupportFileUpload() {
    var isCompatible = false;
    if (window.File && window.FileReader && window.FileList && window.Blob) {
      isCompatible = true;
    }
    return isCompatible;
  }

  // Convert CSV data to JSON format
  function csvToJson(data) {
    var cols = ["Firstname","Lastname","Nickname","Grade"];
    var out = [];
    for (var i = 0; i < data.length; i++){
      var obj = {};
      var row = data[i];
      cols.forEach(function(col, index){
        if (row[index]) {
          obj[col] = row[index];
        }
        else {
          obj[col] = "";
        }
      });
      out.push(obj);
    }
    return out;
  }

  // Generate table for user review and upload button
  function makeTable(data) {
    console.log(data);
    send_data = JSON.stringify(data);
    console.log(send_data);
      var table_data = '<table style="table-layout: fixed; width: 100%" class="table table-striped">';
      table_data += '<th>First name</th><th>Last name</th><th>Nickname</th><th>Grade</th>'
      for(var count = 0; count < data.length; count++) {
        table_data += '<tr>';
            table_data += '<td>'+data[count]['Firstname']+'</td>';
            table_data += '<td>'+data[count]['Lastname']+'</td>';
            table_data += '<td>'+data[count]['Nickname']+'</td>';
            table_data += '<td>'+data[count]['Grade']+'</td>';
        table_data += '</tr>';
        }
      table_data += '</table>';
      table_data += '<p><form action="/uploaded" method="post">';
      table_data += 'Does the data look OK? If so, click to upload.  ';
      table_data += '<button class="btn btn-primary" type="submit">Upload</button><p>';
      table_data += '<input type="hidden" id="data" name="data" value='+send_data+'>';
      table_data += '<input type="hidden" name="class_id" value="{{ class_id }}">';
      table_data += '</form>';
      table_data += 'Otherwise, fix the file and reload.';
      document.getElementById("result_table").innerHTML = table_data;
  }
  </script>

Answer №1

Streamline the JavaScript code to make it simpler. By following this approach, are there any concerns about the JSON data being truncated?


document.getElementById('update-data-from-file').addEventListener('change', function(evt){
  var file = evt.target.files[0];
  document.getElementById('filename').innerText = file.name

  if (file === "")
    return;

  Papa.parse(file, {
    header: true,
    skipEmptyLines: true,
    complete: function(results) {
      json = results.data
      console.log(json)
      // Perform actions with the json data here
    }
  });

  document.getElementById('update-data-from-file').value = ''
})
            
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.0.2/papaparse.min.js"></script>
  </head>
  <body>

    <label>
      Upload CSV
      <input type="file" name="File Upload" id="update-data-from-file" accept=".csv" />
    </label>
    <div id="filename">No file chosen</div>
    
  </body>
</html>
            

Answer №2

The issue arose from the way I was transmitting the JSON string - it lacked quotation marks, causing problems whenever there was a space within a value.

To resolve this: I utilized the JSON data from the aforementioned solution and, prior to sending the JSON string through a POST request, I enclosed it in quotes.

data_to_send = JSON.stringify(json);
data_to_send = "'" + send_data + "'";

I am now able to successfully transmit values containing spaces.

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

Retrieve the browser version through the use of the Selenium WebDriver

Is there a way to retrieve the browser version? >>> from selenium import webdriver >>> driver = webdriver.Chrome() >>> print(version) <-- Any suggestions on how to accomplish this? Chrome 92.0 ...

Using PHP to beautify JSON data

I'm currently working on generating JSON output for a specific JavaScript application, but I'm encountering a formatting issue that the script is not recognizing. Here's how I've structured my JSON so far: // setting up the feed $feed ...

Removing file extensions using Selenium in Python

After utilizing a code snippet for proxy from this source, I encountered difficulties in disabling or removing the proxy extension. Despite my efforts to locate it in the extensions folder within the profile directory, no extensions were found installed vi ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

Creating a customized JSON object with Laravel framework

Hey Team, I'm facing an issue with structuring my JSON output correctly. What I have in mind is the desired output below: { comments: { data: { created_at: "date", other: "etc", from: { username: ...

Tips for retrieving the xpath of elements within a div using python selenium

<div class="col-md-6 profile-card_col"> <span class="label">Company Name :</span> <p class="value">Aspad Foolad Asia</p> </div> For a while now, I've been trying to troublesho ...

Ways to verify AJAX Response String when data format is specified as JSON

When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType to json. If the data processing is successful, a valid JSON string is returned, which works perfectly. However, if there's an error on the webpage, inst ...

Using Python and Selenium, you can locate an element inside another element

I've got the xpath for an element: /html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[6]/div/div/div/div[1] Inside that div, there's another element: /html/body/div[1]/div/div[2]/div[3]/div/div/div/div[2]/div[1]/div[2]/div[ ...

Creating snake_case format for definitions in swagger.json within Dropwizard

I am currently working with the dropwizard framework on a project where I have implemented the @JsonSnakeCase annotation to convert CamelCase format to snake_case. However, when I attempt to generate swagger.json using swagger annotations, the definitions ...

What $TERM should be utilized in order to enable both 256 colors and mouse movement events within Python's curses module?

When I set the TERM environment variable to 'xterm-1003', I can receive mouse move events, but the color display is not great and curses.can_change_color() returns False. os.environ['TERM'] = 'xterm-1003' ... curses.mousemask ...

Tips for setting up my ajax/views method to output a dictionary

Here's the HTML snippet I have along with an AJAX request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"end ...

Is it possible for additional JSON properties to be deserialized into a JObject within a class during the deserialization process?

Imagine we are working with the following JSON data: { "apple": 5, "banana": "yellow", "orange": 10, "grape": "purple", } and a C# class is defined as: class Fruits { public int AppleCount { get; set;} public string BananaColor ...

Enhancing the security of a JSON web service

Having an issue with security of a json web service implementation. I attempted to create a sample web application using a json webservice, but the problem I encountered was that the url was visible on the client side. This means anyone could easily create ...

Deleting a segment of code in HTML with Python

My HTML text is lengthy and follows this structure: <div> <div> <p>Paragraph 1 Lorem ipsum dolor... long text... </p> <p>Paragraph 2 Lorem ipsum dolor... long text... </p> <p>Paragraph ...

When comparing org.json.simple.JSONObject and org.json.JSONObject, the issue of JSONException not being able to be resolved as a

Could someone clarify the distinctions between org.json.simple.JSONObject and org.json.JSONObject? Also, I am encountering an issue with a code that uses org.json.JSONObject and org.json.JSONException. While editing the code in Eclipse (JUNO), it recogniz ...

Error encountered when passing NoneType to .send_keys in Python Selenium while using the Chrome

I'm having trouble inputting my username in the designated field on a website. Although I can open the site and click on the box, no text appears when I try to type. Additionally, a warning popup from Chrome's developer extensions keeps showing u ...

What could be causing my Selenium URL_to_be statement to fail?

Why won't Selenium recognize my manual visits to publish0x.com? Does anyone have a solution for this? I need to complete the captcha manually on the login page and then have the script continue after logging in and landing on the main page. from sele ...

Ways to enhance the size of aircraft in Plotly

Upon analyzing the code snippet import pandas as pd import plotly.graph_objects as go import numpy as np df = pd.read_csv('https://raw.githubusercontent.com/tiago-peres/immersion/master/Platforms_dataset.csv') fig = px.scatter_3d(df, x='Fu ...

Using Python with PyQt5, create a QTableWidget that incorporates LineWrap functionality for wrapping

Is it possible to enable line wrap on a QTabelWidget in PyQt5 when trying to display long strings from an Excel document? I have attempted using the QTextDocument class without success. Below is a simple example with two constant strings to be displayed in ...

Multitasking with Gevent pool for handling multiple nested web requests

I am working on setting up a pool with a maximum of 10 concurrent downloads for organizing web data. The goal is to download the main base URL, parse all URLs on that page, and then proceed to download each individual URL, but maintaining an overall limit ...