Changing a zero-prefixed string into JSON format using Swift 4

When attempting to encode an integer that starts with a 0 into JSON using swift 4, I encountered an issue.

Even though I am utilizing a standard JSONSerialization library, I am facing difficulties in serializing the data after converting the string to utf8.

let code = "012345" // sample code
let body = "{\"code\": " + code + "}"
let stringData = body.data(using: .utf8)!
let jsonArray = try? JSONSerialization.jsonObject(with: stringData, options : .allowFragments) [returns nil]
let data: Data? = try? JSONSerialization.data(withJSONObject: jsonArray as Any, options: .prettyPrinted)

The problem arises on the second to last line (starting with let jsonArray), where it returns nil. Interestingly, changing the code to "112345" eliminates this error. Any assistance would be greatly appreciated. Thank you!

Answer №1

Instead of manually constructing a string, consider utilizing Dictionary along with JSONSerialization to generate the data as shown below:

let code = "987654"
let jsonData: [String: Any] = ["code": code]
do {
    let serializedData = try JSONSerialization.data(withJSONObject: jsonData, options: .fragmentsAllowed)
    print(String(data: serializedData, encoding: .ascii)!)
} catch {
    print(error)
}

Result

{"code":"987654"}

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

Switching XML to JSON using React.js

Currently, I am in the process of developing an application with a requirement to retrieve data from a web API that provides XML responses. However, my objective is to obtain this information in JSON format, but unfortunately, the API does not offer suppor ...

Function not executing on button press in React.js

I am trying to trigger a function upon clicking a button, but unfortunately, nothing is happening. Despite adding a console.warn() statement inside the function, it doesn't seem to be logging anything. I've looked through similar Stack Overflow s ...

Utilizing React JS to dynamically populate a table with data from an external JSON file

As a newcomer to the realm of React, I am facing challenges in displaying my JSON data in a table. class GetUnassignedUsers extends React.Component { constructor () { super(); this.state = { data:[] }; } com ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Show and Arrange Various Key-Object Data pairs

I'm facing a challenge with mapping and displaying a JSON file in a different structure. I need help figuring out how to map the data properly. Here's the JSON file: var data = { "megamenu": [ { "name": "level1.2", "link": "#", ...

I am facing an issue with Lotties having a black background in my NextJS project. Is there a way to make them transparent

I am facing an issue with my LottieFiles (JSON) displaying a black background when imported into my NextJS project. Despite trying to set background='transparent' on both the Player and parent div, the problem persists. I made sure to export my ...

Having difficulty displaying JSON data in a react component

I am currently working on parsing JSON data retrieved from an Ajax call in order to display it in a table using the React DataTable component. However, I have encountered a problem while trying to store the data in a state variable using the setState metho ...

Tips on efficiently compressing JSON data in order to receive it using the bodyParser.json method

I am looking to compress a JSON file before sending it to my server. I want to handle the compression in the browser by utilizing an explainer and then pass it to the bodyParser.json middleware. The client-side function would look something like this: e ...

Accessing a specific data point from a Rest Api with React JS

How can I extract the value '00000000000000000000000000000000' that comes after clusters in the links->href in a Rest Api response? [{ "analysisUnits": [ { "links": [ { "href": "http://127.0. ...

Updating subdata in an array using Reactjs handleChange

I am facing an issue with my handleChange function. While I can easily change data in the same directory without any problem, I'm struggling to update sub-data. I would like to find a clean solution for this without having to add extra functions withi ...

Tips for preserving axois GET response as a JSON object or in its original form upon arrival

export class LoadProfile extends Component { state = { data: '' } componentDidMount() { axios({ url: 'http://localhost:8080/profile/all', method: 'GET', responseType: 'json', ...

I am struggling to figure out the best way to save JSON data retrieved from an API request in a Node.js Express server, and then efficiently send it to a React Native client

My Node.js server is up and running with an app.js file structured like this: var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-pars ...

Avoiding repetition in json array using reactjs with the help of axios

After receiving guidance from @Akrion, I managed to resolve the issue! Check out my comments below our conversation for the solution. I am relatively new to reactJS and axios, but I recently collaborated with a classmate on a project. Now, I find myself s ...

What are some methods for singling out a specific table row?

When working on my app, I faced the task of importing a JSON file and displaying its contents in a table with 3 columns. However, there are two main issues that arose: Utilizing array index for the row key is not recommended due to the table also having ...

Step-by-step guide on writing to a JSON file using Node.js

I am currently developing a Facial Recognition web application using React for the frontend and Node.js for the backend. You can find more information about my project here. So far, I have completed the frontend part where users manually add 128-d descript ...

What is the process of importing a JSON data file and utilizing it within a React component?

As a beginner in React, I am struggling with the concepts of importing, exporting, and rendering components. I have a fakeData.json file within the same src/components folder as the component I want to render. Let's take a look at the structure: < ...

Updating the value of a different key within the same object using React Formik's setFieldValue方法

My objective is to automatically select a value in an option select when the onChange event occurs, and then use setFieldValue to set values for 2 Fields with key-value pairs within the same object. The issue I'm facing: Why does calling setFieldValu ...

Images from JSON cannot be loaded in ReactJS

It seems that importing image URLs from a JSON file is not working as expected, resulting in certain issues. However, when importing them using the syntax {require("hardcoded URL")}, it works fine. But if variables are used as shown in the image below or l ...

Preparing my JSON data for visualization on a chart

I have successfully retrieved data using this API, but now I need to transform it into a chart within my react project. As a newcomer to JS and React, I am struggling to create a chart with the JSON data. My objective is to display prices by bedrooms over ...