Instructions for converting a JSON string into the proper format for a POST request in Swift

After using significant string interpolation, I have generated this JSON structure:

{
    "headers":{
        "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="11747c70787d517469707c617d743f7e6376">[email protected]</a>",
        "rank":0,
        "blue":false,
        "team":1000,
        "round":33,
        "tournament_id":"7F98sdh98aFH98h"
    },
    "data":{
        "start_position":0.0,
        "crossed_line":true,
        "end_platform":true,
        "lift":0,
        "first-actions":[
            {
                "timestamp":1520403299.17746,
                "action":"0_0_1"
            }
        ],
        "second-actions":[
            {
                "timestamp":1520403299.96991,
                "action":"0_0_2"
            }
        ]
     }
}

In an attempt to add this JSON to my POST request's httpBody, I used the following code snippet:

request.httpBody = json.data(using: .utf8)

However, it led to a 422 error.

On the Server side, everything in the string was treated as one header:

--- NEW REQUEST ---
Time: March 6th 2018, 8:47:23 pm (1520398043327)
IP: [REDACTED]
Request: [REDACTED]
req.body = {'{"headers":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3a323e36331f3a273e322f333a71302d38">[email protected]</a>","rank":0,"blue":false,"team":1000,"round":20,"tournament_id":"7F98sdh98aFH98h",},"data":{"start_position":-36.5385,"crossed_line":true,"end_platform":true,"lift":0,"first-actions":[{"timestamp":1520398021.45196,"action":"0_0_1"}],"second-actions":[{"timestamp":1520398022.73314,"action":"0_0_2"}]}}':''}
Auth: [REDACTED]
Auth level: 10

Then, I realized that it needs to be sent as a JSON Object instead of a string. Various methods were attempted, like converting json into a Dictionary, but then converting to Data resulted in a runtime error.

Can you provide guidance on how to convert the string into the correct format?

UPDATE: Outcome from Dávid's response:

--- NEW REQUEST: 60 ---
[REQ 60] Time: March 7th 2018, 8:52:39 pm (1520484759369)
[REQ 60] IP: [REDACTED]
[REQ 60] Request: [REDACTED]
[REQ 60] req.body = { '{"headers":{"team":"1000","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17727a767e7b57726f767a677b7239786570">[email protected]</a>","rank":"0","blue":"false","round":"22","tournament_id":"7F98sdh98aFH98h"},"data":{"lift":"0","crossed_line":"true","end_platform":"true","first-actions":[{"timestamp":0,"action":"0_0_0"},{"timestamp":1520484747.061681,"action":"0_0_1"}],"second-actions":[{"timestamp":0,"action":"0_0_0"},{"timestamp":1520484747.9255838,"action":"0_0_2"}],"start_position":"0.0"}}': '' }
Auth: [REDACTED]

Answer â„–1

To start, it's important to note that constructing JSON objects using String interpolation is not the recommended approach. Instead, you should create a proper object like a `Dictionary` for this purpose.

Once you have collected all the necessary data in a variable of type `Dictionary`, you can then convert it into JSON format utilizing either the `JSONSerialization` or `JSONEncoder` APIs.


let email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="254048444c4965405d44485549400b4a5742">[email protected]</a>"
let dictionary = ["headers":["email":email,"rank":0, "blue":false,"team":1000,"round":33, "tournament_id":"7F98sdh98aFH98h"], "data":[ "start_position":0.0, "crossed_line":true, "end_platform":true, "lift":0, "first-actions":[["timestamp":1520403299.17746,"action":"0_0_1"]],"second-actions":[[ "timestamp":1520403299.96991, "action":"0_0_2"]]]]
do {
    let jsonEncodedDictionary = JSONSerialization.data(withJSONObject: dictionary)
    request.httpBody = jsonEncodedDictionary
} catch {
    //It's essential to handle errors appropriately based on your specific requirements
    print(error)
}

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

Is there a way to combine two JSON objects within an Android spinner?

After fetching data from my database, is it feasible to combine both objects into a single object? Below is the Android code snippet for retrieving data for a spinner: spinner1 = (Spinner) findViewById(R.id.sp1); final List<String> list1 = ...

Retrieve values from a database table in Laravel by comparing the IDs stored in one table in JSON format with the IDs in another table

My database table is called journal_details and it contains a column named transaction_by_to. I store values of account_head_id in JSON format within the transaction_by_to column of the journal_details table. Now, I need to execute a select query to retrie ...

Navigate through the JSON dataset

I am struggling with looping out JSON-data in an HTML list using PHP. The structure of the JSON data is as follows: { "msg": [ "msg text 1", "msg text 2", "msg text 3", "msg text 4", "msg text 5", "msg text 6" ] } My current P ...

JSON data returned from an AJAX request could be utilized to populate a

Need help with displaying data in two dependent select boxes based on the selection of the first box. <?php $con=mysql_connect("localhost","root","root"); mysql_select_db("register",$con); ?> <!DOCTYPE html> <html&g ...

The JSON data is being posted, but the table remains empty and does not populate

UPDATE: Tried modifying the Jquery code to dynamically recreate rows, but it still doesn't work Reorganized my table structure with no success I have a PHP script that encodes my database table into an array. When I echo the json_encode, everything ...

Looking to fetch JSON data from a private IP that is not accessible to the public

Is there a way to retrieve JSON data from a location that is only accessible within a company's firewall? The address I am trying to access is: http://12.34.56.789:8983/app/collection/select?q=*%3A*&wt=json&indent=true My application can be ...

Encountering an issue when attempting to save JSON data in the database: unable to convert object into a string

To summarize, my data is stored in Javascript: JSONdata = { name: form.name.value, address1: form.custa.value, address2: form.custa2.value, postcode: form.custpc.value, order: fullorder, cost: document.getElementById('total&ap ...

Bug in data parsing process

Check out this code snippet: $_REQUEST[ 'LOM' ] var_dump($_REQUEST[ 'LOM' ]); After running the code, the output shows a JSON structure like this: { "id":0, "type":"root", "related_dropzone_id":0, "related_dropzone_order" ...

Changing the format of JSON output in Laravel

Help me clean up my JSON output by removing unnecessary elements. This is my current Output: [ { "current_page": 1, "data": [ { "_id": "6580f69587f0f77a14091c22", ...

Unpacking key-value pairs from a JSON array in PHP and restructuring the data

Looking for suggestions on how to transform the JSON structure shown below: $jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"}, {"Level":"399.2023%","Product":"Coffee","Temperature":"34"}, {"Level":"109.2023%","Product ...

Sending post parameters from Angular and receiving JSON data from PHP using $http

Exploring the world of Angular and delving into the realm of $http, I find myself faced with a perplexing challenge: How to post parameters using $http (necessary for PHP to execute the call) Retrieve a JSON response from that call Here's what I&ap ...

In PHP, extract the initial three characters from each item within a foreach loop

In the following code snippet, I am trying to extract data from a JSON array and store it in a variable: $arr = json_decode($jsondata, TRUE); $arr2 = $arr['items']['item']; echo '<ul>'; foreach ($arr2 as $val) { echo &a ...

Developing a JSON object with PHP

Is there a way in PHP to generate the following JSON structure? { "actors": [ { "name": "Brad Pitt", "description": "William Bradley 'Brad' Pitt is an American actor and film producer. He has received a Golden Globe Award, a Sc ...

When using google search with json_decode, the result returned is null

$query = "Poultry meat is a major source of animal protein considering"; function fetch_google($query) { $cleanQuery = str_replace(" ","+",$query); $url = 'http://www.google.com/search?q='.urlencode($cleanQuery); $data=file_get_contents($url ...

What is preventing me from retrieving the JSon data?

I've been attempting to retrieve the count of a variable through ajax, but I keep receiving a "fail" message every time Here is the php file that runs perfectly when tested: <?php $conn= mysqli_connect("localhost","root","") or die ("could not ...

What's causing my variables to be returned as null in the alerts?

Why am I receiving null values when alerting my variables? I'm attempting to pass a string stored in a variable from an external JavaScript file back to the main page using alerts. Initially, I suspected that the JavaScript was not fetching data cor ...

Convert the value to JSON format by utilizing the PHP GET method

After retrieving a value using the GET method in my PHP file, I am attempting to access it. Below is how my PHP file appears: <?php include 'Con.php'; header('content-Type: application/json'); $catid = $_GET["CatId"]; //array ...

Use PHP shopify_call to sync and adjust the inventory in your Shopify store

I am in the process of developing a PHP-based API for Shopify to facilitate updating the inventory_quantity of a product. Below is the JSON representation of my product: "variants": [ { "id": 1234567890123, "produc ...

What is the process for retrieving external JSON using PHP with a content-type of text/plain?

I am attempting to retrieve an external JSON response using my PHP backend. However, I am encountering an issue where the external endpoint is returned with the Content-Type: text/plain;charset=utf-8, resulting in unreadable content. string 'ï¿½ï¿½ï¿ ...

Retrieve JSON data from a PHP script

Hey there everyone, I'm new to working with JSON and I need some help. I have data (an array) that was sent from a PHP file in encoded format, and all I want to do is simply get this data and display an alert with it. The object sent from the PHP fi ...