The process of isolating each variable within a JSON data structure

After making an ajax call, my JSON data is currently displayed in this format:

{"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}

However, I would like it to be formatted like this:

{"main_object":{"language":"nl_NL","getExerciseTitle":"asd","question_takeAudio_exerciseWord":["asd"],"Syllablescounter":["ASDasd",""]}}

The only addition I want to make is the "id":"new".

This is the ajax call I am using (the JSON data initially resembles the first format upon initiation of the ajax call)

 function saveExerciseAjaxCall() {
  $("#my_form").on("submit", function (event) {
    event.preventDefault();
         $.ajax({
              url: 'saveJson.php',
              type: 'POST',
              data: {id: getUrlParameter('id'), formData: $('#my_form').serialize()},
              dataType: 'json',
          }).done(function (response) {
              window.location = 'index.php';
          });
 });
}

Edit: Ouni requested that I provide details of what occurs in the php script, so here it is:

<?php
include_once('database_json.php');
$data = $_POST;
//Initializing an empty array.
 $errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
    if (count($database['data']) == 0) {
        $ID = 0;
    } // concluding database['data'] count 0.
    else {
        $maxID = max($database['data']);
        $ID = ++$maxID["id"];
    } // concluding the else statement with max ID.
    $newJsonFile = 'jsonData_' . $ID . '.json';
    $newJsonFilePath = 'json_files/' . $newJsonFile;
    //Creating a new database exercise_txt
    $newArrayData = array(
        'id' => $ID,
        'exercisetitle' => $data['formData']['getExerciseTitle'],
        'language' => $data['formData']['language'],
        'file' => $newJsonFile
    );
    $database['data'][] = $newArrayData;
} // } at line 34 seems lost...?
else {
    $index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
    $correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
    $newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
    $newJsonFilePath = 'json_files/' . $newJsonFile;
    //Creating a new database exercise_txt
    $newArrayData2 = array(
        'id' => (int) $data['id'],
        'exercisetitle' => $data['formData']['getExerciseTitle'],
        'language' => $data['formData']['language'],
        'file' => $newJsonFile
    );
    $database['data'][$index] = $newArrayData2;
} // closing off the else statement
$newExerciseData['main_object'] = $database['data'];
header('Content-Type: application/json');
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.

How can I achieve this desired formatting? The issue doesn't seem to lie within my saveJson.php file. Rather, I suspect it might be originating from my ajax call since the JSON data starts as the first piece shown when I include the id: getUrlParameter('id')

Answer №1

Let's zero in on your question itself, setting aside the valid comments about your overall approach. It appears that you have data in a querystring format that needs to be parsed into JSON format. Querystring format is data that resembles this:

language=nl_NL&getExerciseTitle=test

You are aiming for something like this:

{
  language: "nl_NL",
  getExerciseTitle: "test"
}

and so forth.

One way to achieve this is by utilizing a library that can handle this process effortlessly. An example would be the query-string package.

For instance, when provided with a string:

 const result = "language=nl_NL&getExerciseTitle=test";
 const parsed = queryString.parse(result);

you will receive the expected result.

Answer №2

Learn how to extract data from your query string using pure JavaScript, no need for any external libraries:

const queryString = {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
const tempData = Object.assign({}, queryString);
tempData.formData = decodeURIComponent(queryString.main_object.formData)
  .split("&")
  .reduce((result, data) => {
    const parts = data.split("=");
    let key = parts[0];
    const value = parts[1];
    const arrayIndex = key.indexOf('[');

    if (arrayIndex > 0) {
      key = key.substring(0, arrayIndex);
      if (result[key] === undefined) { result[key] = []; }
      result[key].push(value);
    }
    else {
      result[key] = value;
    }
    return result;
  }, {})
;
console.log(tempData.formData);

I highly recommend sticking with vanilla JS whenever you can. This way, you grasp the fundamentals and have the flexibility to customize it as per your requirements in the future.

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

Unable to display label in form for Angular 2/4 FormControl within a FormGroup

I'm having trouble understanding how to: Use console.log to display a specific value Show a value in a label on an HTML page Display a value in an input text field Below is my TypeScript component with a new FormGroup and FormControls. this.tracke ...

Load images in advance using this script

Using a script to load images on two websites, the image is placed inside a div with the ID div-to-load-external-image Encountering an issue where PageSpeed Insights advises to preload these images, seeking guidance... Any assistance will be appreciated. ...

Switching the cursor to the following input after a paste event using JQuery

I am currently working on an HTML form that consists of multiple input boxes. I'm looking to focus on the next input box after pasting content into one of them. Below is the code snippet I have been using: $("input").bind('paste', function( ...

Customize the serialization of a single object in Newtonsoft.Json

When comparing hashes of serialized objects on the server and client, it is important for the JSON rendering to be identical on both sides. Currently, there is an issue with a number field being serialized differently in JavaScript and .NET - causing the h ...

Transferring a variable from an Angular 2 constructor into the template via the then statement

I'm struggling with implementing a secure login system. My goal is to first check the device's native storage for an item named 'user', then verify if the user exists in our database, and finally retrieve the unique id associated with t ...

Access data from JSON array in Angular 2

I'm facing a basic issue here. I have a JSON file named pageDefinition.json that is being loaded into my component. Here's how the JSON data looks: ... "testArray": [ {"id": 0, "name": "row1"}, {"id": 1, "name": "row2"}, {"id": 2, "n ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Service Worker's fetch event is not triggered upon registering the service worker

Service Worker is a new concept to me. As I delved into learning how to incorporate Service Worker into My Next.js Application, I encountered an issue with the fetch event handler. Oddly enough, the fetch event handler doesn't trigger upon initially r ...

Is it just me or does my node server come preconfigured with CORS enabled? What am I overlooking here?

I have a simple node and express server set up here. Surprisingly, even without any middleware, I am able to successfully log the response from an axios request made to google.com. Doesn't this usually trigger a cors error, requiring some form of midd ...

Utilize a boolean attribute for filtering with jq in a deeply nested array

How can I use jq to filter all connections where field.usesEncryption is true in the provided JSON data? { "connections": { "connection": [ { "field": [ { "id": "url&quo ...

Refreshing a div using Php and ajax at specific intervals

Can I load the div values automatically when the page loads along with after a time interval? How can I achieve this? <script type="text/javascript> $(document).ready(function() { setInterval(function(){ $("#Te ...

Having trouble getting unique input values to pass through ajax

For the past couple of weeks, I've been searching for a solution to my issue. The problem arises in my PHP foreach loop where I have div tags representing rows of data fetched from the database. Each div row contains HTML input elements and a button t ...

Retrieve key-value pairs from a database and store them as variables in PHP before transferring them into an array in JavaScript

My challenge lies in loading Chinese characters as keys and their English translations as values from a database into a PHP array, so that I can use them on the client side in JavaScript. The process involves fetching key:value pairs from PHP into a JavaSc ...

What is the process for adding routes prior to implementing jsonwebtoken?

I am currently working with jsonwebtoken and I have some questions about how it functions. I have regular sign-in and sign-up routes that should come before the .verify function. Although I have experience using jwt in the past, this is my first time imple ...

What causes Three.js OBJ conversion to render as mesh successfully but log as undefined?

I'm just getting started with Three.js and I'm experimenting a lot. Although I'm new to Javascript as well, the issue I'm facing seems to be more about variable scoping and callback function protocols than it is about Three.js itself... ...

Utilizing Pushwoosh to Send Push Notifications via VB.net and JSON

I'm currently trying to send a message to a device using the Pushwoosh API through my VB.Net application with a premium account. The code seems to be working fine, but I keep receiving a 400 error code from the server. Any suggestions on what might be ...

Having issues with setting up nodejs on kali linux

Whenever I try to execute the configure script ./configure for nodejs installation, it fails to run successfully. Traceback (most recent call last): File "./configure", line 19, in <module> from distutils.spawn import find_executable ModuleN ...

Use $parse to extract the field names that include the dot character

Suppose I have an object with a field that contains a dot character, and I want to parse it using $parse. For instance, the following code currently logs undefined - var getter = $parse('IhaveDot.here'); var context = {"IhaveDot.here": 'Th ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...

Set up a single array containing multiple objects in a table, each with its own unique set of keys

I am currently developing an application that retrieves data from one or multiple databases, each with different names and varying numbers of columns. The goal is to consolidate this data into a single report screen and export it as a table. While the tabl ...