How can we change the contents of players into objects?

How can the content within players be transformed to an object?

{
    "players": "a:36:{i:0;a:3:{s:9:\"player_id\";i:108035;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:1;a:3:{s:9:\"player_id\";i:134595;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:2;a:3:{s:9:\"player_id\";i:107807;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:3;a:3:{s:9:\"player_id\";i:107795;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:4;a:3:{s:9:\"player_id\";i:108276;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:5;a:3:{s:9:\"player_id\";i:107799;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}...
 

Answer №1

You have the option to quickly convert your code using regex, but it may not be the safest method. Consider using a loop for parsing objects instead:

let obj = {
    "players": "a:36:{i:0;a:3:{s:9:\"player_id\";i:108035;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:1;a:3:{s:9:\"player_id\";i:134595;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}i:2;a:3:{s:9:\"player_id\";i:107807;s:4:\"team\";s:5:\"team1\";s:4:\"role\";s:4:\"main\";}}",
    "events": "a:13:{i:0;a:7:{s:4:\"type\";s:4:\"goal\";s:4:\"team\";s:5:\"team2\";s:4:\"time\";i:10;s:6:\"player\";s:11:\"David Silva\";s:4:\"note\";s:14:\"Bernardo Silva\";s:9:\"player_id\";i:107941;s:10:\"player2_id\";i:107952;}}",
    "stats": "a:17:{i:0;a:3:{s:5:\"title\";s:12:\"Yellow cards\";s:5:\"team1\";i:2;s:5:\"team2\";i:3;}}"
}

// This code can be enhanced with a loop for parsing
Object.values(obj).forEach((str) => {
  str = "{" + str + "}";
  str = str.replace(/([asi](?:\:[0-9]+)*):/g, '"$1":');
  str = str.replace(/;/g, ',');
  str = str.replace(/}"/g, '},"');
  str = str.replace(/,}/g, '}');

  str = str.replace(/"i":([0-9]*),"(a:[0-9]+)":{/g, '"$2_$1":{');

  console.log(JSON.parse(str))
});

Parsed Output :

{
  "a:36": {
    "a:3_0": {
      "s:9": "player_id",
      "i": 108035,
      "s:4": "main",
      "s:5": "team1"
    },
    ...
  }
}
{
  "a:13": {
    "a:7_0": {
      "s:4": "note",
      "s:5": "team2",
      "i": 107952,
      "s:6": "player",
      ...
    }
  }
}
{
  "a:17": {
    "a:3_0": {
      "s:5": "team1",
      "s:12": "Yellow cards",
      "i": 2
    },
    ...
  }
}

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

What is the best way to capture a form submission when there are no errors?

My form includes a validation check for valid fields upon submission. Here is an example of how it is structured: <form class="form-horizontal" method="post" action="#" name="basic_validate" id="basic_validate" /> <div class="con ...

Is it a good idea to combine both dynamic and static information within a react state?

As I ponder the data structure of my application, I've stumbled upon an intriguing question: Within my code, there exists some data that is predetermined and will remain constant throughout the lifespan of my app. Let's consider this data to be ...

Guide to updating the d attribute of a path element in Angular 2

I've been working on an Angular2 Project and I have a service file that allows me to access data in my component's .ts file. class Coordinate { x:number; y:number; } class Data { ..... coordinates: Array<Coordinate>; ......... } M ...

What is the best way to setup a function parameter to store responses from an inquirer.prompt inquiry using JavaScript and integrating with MySQL?

How can I incorporate function parameters to handle answers from an inquirer.prompt question in JavaScript? While I already know how to achieve this without using variables, I aim to enhance the usability of my addToTable function by utilizing parameters ...

Looking to set an object value as optional in JavaScript?

Hello, I am currently in the process of developing a web application using ReactJS with Auth0 for user authentication. In order to update user information on my backend, I am utilizing state to store the necessary data. My challenge lies in allowing eith ...

"An issue with Angular Http Get causing Status 0 to be consistently returned when using ng

I've been attempting to make this function properly. The concept is simple: click the tag, which then triggers a REST service call that returns a JSON result. I extract the country name from the response just for testing purposes. I'm currently u ...

a helpful utility type for extracting a union from a constant array of strings

I create string arrays using const assertions and then use them to generate union types. const elements = ["apple", "banana", "orange"] as const; type elementsUnion = typeof elements[number]; // type elementsUnion = "appl ...

Modify one of the values within a .ts file and then be sure to save the changes within the Ionic

My application saves data in a .ts file. There is a function that can modify a boolean value (displayed) within this file. Is it possible to persist these changes in the file? I want the values to be retained even if the user closes and reopens the applica ...

data argument cannot accept an array entry - internal server issue

My attempt to call a C# MVC controller method from a custom JavaScript script using Ajax seems to be encountering an issue with accepting array entries as arguments within the Ajax request. I tested assigning them to non-array variables, which worked, but ...

core.js:12853 Error encountered when trying to use 'ngIf' on a 'div' element that is not recognized as a valid property

I am currently utilizing Angular 9. and I am faced with a scenario where I need to load dynamic components Within one of my components, I encountered the following warning core.js:12853 Can't bind to 'ngIf' since it isn't a known pro ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Encountering a 'SyntaxError: Unexpected string' error close to the import statement while using ts-node-dev

Struggling to incorporate TypeScript libraries with Node, I keep encountering SyntaxErrors. When running the dev script from package.json using ts-node-dev, the errors tend to appear near the import statements. Unsure if it's an issue with my tsconfig ...

Upcoming 13.4 Error: NEXT_REDIRECT detected in API routes

Here is the code snippet from my /app/api/auth/route.ts file: import { redirect } from 'next/navigation'; export async function GET(req: Request) { try { redirect('/dashboard'); } catch (error) { console.log(error); ...

When a user inserts particular text into the form, redirect them to a specific page upon submission

On my website, users have the option to learn either web design or game design by filling out a form on the index page. Currently, the only function that is working correctly in my script is the alert that notifies users if they haven't made a selecti ...

Displaying a dialog or popup in React Native when catching errors

Exploring React Native has been quite a journey for me, especially when trying to implement a popup for error handling. Despite numerous attempts, I haven't been successful in getting it to work as desired. The code snippet below captures my current i ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

Protractor's modal dialogue displays numerous outcomes when accessing ng-repeater elements

Trying to click on an element located within a repeater has presented some challenges. The issue arises from the fact that it is a modal dialog and returns multiple elements for the repeater. Each page in our application functions as a modal dialog, leadin ...

AngularJS's $filter directive and Javascript syntax

Attempted to extract specific data from a JSON file using $routeParams:id. Typically, I would use the following method: var eventId = $routeParams.eventId; $http.get('json/events.json') .success(function(data){ angular.forEach(data,functio ...

Tips for sending properties to a child component in a React Native project using TypeScript

Here is the setup in my parent component: const [OTPNotify, setOTPNotify] = useState("flex"); const closeOTPNotify = () => { setOTPNotify("none"); } <OTPRibbonComponent onCancel={closeOTPNotify} display={OTPNotify}/> Now, ...

Unable to modify the color of a THREE.Mesh material that is present in the scene during runtime

I have already added some mesh to the scene. I am attempting to change the color of the material. The color change is done via a color palette in the menu. I am utilizing a jQuery plugin for this: I am aware that the color palette can provide me with HSB ...