Guide on parsing non-JSON data using Hemera

I'm a newcomer to the world of Json and JavaScript. I currently have an url that provides a JSON response. However, the issue lies in the fact that the format is incorrect. Please refer to my response below:

var pd={ player: 
   { id: 363609002,
     game: 'bf4',
     plat: 'pc',
     name: 'm4jes',
     tag: 'BPt',
     dateCheck: 1487204427149,
     dateUpdate: 1474581052618,
     dateCreate: 1384980182606,
     dateStreak: 1474581052618,
     lastDay: '20160715',
     country: '',
     countryName: null,
     rank: 
      { nr: 121,
        imgLarge: 'bf4/ranks/r121.png',
        img: 'r121',
        name: 'Major General II',
        needed: 16110000,
        next: 
         { nr: 122,
           imgLarge: 'bf4/ranks/r122.png',
           img: 'r122',
           name: 'Major General III',
           needed: 16750000,
           curr: 16720600,
           relNeeded: 640000,
           relCurr: 610600,
           relProg: 95.40625 } },
     score: 16724643,
     timePlayed: 1476950,
     uId: '2832665149467333131',
     uName: 'm4jes',
     uGava: '721951facb53ed5632e196932fb6c72e',
     udCreate: 1319759388000,
     privacy: 'friends',
     blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
     blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
     editable: false,
     viewable: true,
     adminable: false,
     linked: false },}

Based on the above response, I need to extract the following output:

{
  game: 'bf4',
  plat: 'pc',
  name: 'm4jes',
  tag: 'BPt',
  score: 16724643,
  timePlayed: 1476950
}

What method should I employ in JavaScript to achieve the desired result?

Answer №1

Firstly, it's important to note that the URL is not providing a JSON response but rather a JS object literal. The distinction is discussed here.

To extract the string from the URL, you can utilize the jQuery method get():

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
  //Insert additional code here
});
</script>

Subsequently, jqxhr.responseText contains the string corresponding to the desired object. By using eval, we convert this string into an object:

pd = eval(jqxhr.responseText);

Now, we have a JS object literal with various name/value pairs. To retrieve specific values, simply use dot notation. For instance, accessing the game name can be achieved as follows:

pd.player.game

This results in:

var myNewObject = {
   game: pd.player.game,
   plat: pd.player.plat,
   name: pd.player.name,
   tag: pd.player.tag,
   score: pd.player.score,
   timePlayed: pd.player.timePlayed,
 }

Lastly, conversion of this JS object literal into JSON format can be done using the JSON.stringify() method:

console.log(JSON.stringify(myNewObject, null, '\t'));

The desired result is displayed:

{
    "game": "bf4",
    "plat": "pc",
    "name": "m4jes",
    "tag": "BPt",
    "score": 16724643,
    "timePlayed": 1476950
}

Here is the complete code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
  pd = eval(jqxhr.responseText);

  var myNewObject = {
   game: pd.player.game,
   plat: pd.player.plat,
   name: pd.player.name,
   tag: pd.player.tag,
   score: pd.player.score,
   timePlayed: pd.player.timePlayed,
 }

 console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>

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

Maintain the same UI appearance when the checkbox state is altered

<input type="checkbox" [(ngModel)]="rowData.is_permitted" (change)="changeStatus()"> changeStatus() { rowData.is_permitted = true; } When I uncheck the checkbox but conditionally want to select it again, the flag is updated but does not affect the ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

Acquiring JSON data within a JavaScript function using PHP

Requesting assistance on reading a JSON value using the code below, to retrieve data based on the $movieID. <script> function bookBTN(x) { <?php $url = 'http://movie.com/movieOne?seatNum=' . x; $jsonURL = file_get_ ...

Create a dynamic animation page using Node.js, then seamlessly redirect users to the homepage for a smooth user

Good day everyone! I've decided to change things up with my latest query. I'm currently working on adding a loading page animation that will show for 3 seconds when visiting the '/' route, and then automatically redirect to the home pag ...

How does the magic of JSON.stringify seamlessly convert to my DTO object effortlessly?

I am working with jQuery and have a specific object set up: function SaveRequest() { var request = BuildSaveRequest(); $.ajax({ type: "POST", processData: false, data: JSON.stringify({'model':request}), url: "somepage.aspx/JsonS ...

How about: "Adding code to a specific location in Monaco editor using programming methods"

I have encountered a two-part issue. The first part involves retrieving the editor content using getValue(), which provides the raw text from the Monaco editor. If I need to append new code after a specific code block, how can this be achieved? Although I ...

Troubleshooting problems with populating select options using jQuery on click

After successfully creating a sample in jsfiddle http://jsfiddle.net/9vkk5/ to demonstrate my issue, I have managed to populate the select with data from a database using the following code: $.ajax({ type: "POST", url: "load.php?type=clients", ...

The program encountered an issue where it was unable to access the 'email' property due to its null value

While implementing form validation for email in my Angular 5 template driven form, I encountered the following error - ERROR TypeError: Cannot read property 'email' of null. Below is the snippet of HTML code containing the form structure: < ...

retrieving information from a JSON document

Within my application, I am utilizing a child process to run a script which then produces a result in stdout. I am currently using res.json(stdout) to transmit this output to the variable data in app.component. My goal is to extract specific data from th ...

Automatically refreshing content (e.g. button click updates div) and changing the URL on the webpage without refreshing, allowing users to stay on the current page even after manually refreshing

Hey there! I've been struggling to find a solution for this problem and haven't had any luck so far. I've been scouring the internet for answers but nothing seems to fit. The challenge: I am in need of a dynamic navigation system for an admi ...

Filling a ButtonGroup in React with Buttons from an array

When trying to populate a ButtonGroup with Buttons using array.map(), I encounter an issue where the buttons do not appear. Interestingly, I used the same method successfully to populate a DropdownButton with MenuItems. Here is the functional DropdownButt ...

The second function in Vue.js was unable to initialize the data field within data() due to a missing call for assistance

I have very little experience working with vue js. There are two functions that I am using: loadComponentsOfUser() and loadUserId(). The loadComponentsOfUser() function depends on the userID field being loaded by the loadUserId() function. data() { retu ...

Expanding the ul height with animation when the page loads

Hi there, I am a beginner looking to create a ul list that increases its height with animation when the page loads. Can this be achieved with CSS? Any assistance would be greatly appreciated. <ul> <li><a href="/">title 1</a>& ...

Unlock the power of AJAX in your WordPress site

I've been exploring the realm of Javascript and AJAX lately. I feel like I'm so close to getting it right, but there's something off with how I'm integrating WordPress ajax functions. I've spent a lot of time going through the docu ...

Refresh a different Angular Controller after submitting a POST request

Just to clarify, I am looking to dynamically reload another controller with new data after a POST request without refreshing the page. Here is my code: No issues with saving data to the database. Script var app = angular.module('userBase', []) ...

Working towards ensuring my website is responsive

Hello, I am a CSS beginner currently working as an intern. My task is to make a website's CSS compatible with Internet Explorer, and then make it responsive and scalable. Essentially, the design should retain its appearance when the window size change ...

Consistently receiving the identical result even when the checkbox remains unselected

Displaying a Checkbox Input <input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" /> The checkbox input will always have the value "AllValue ...

Navigating forward slashes in JSON within a Java/Spring application: tips and tricks

In my application, I have a function that efficiently parses JSON data received through Postman and uses the GSON library to populate an object. The object is then returned as JSON to the user. However, there is one issue with this process - one of the va ...

How can custom CSS and JS be loaded in Sencha Touch based on the user's device - PC, tablet, or smartphone?

Is there a way to configure a webpage so that when the user is accessing it from a PC (using Safari/Chrome/Firefox), they see the "normal" version of the page, but if they are using an iPad to view the same URL, they get Sencha Touch (css, js) files in t ...

What is the best way to retrieve a list of players using a foreach loop from my JSON file?

Is there a way to generate a list of players and their respective play times? I attempted to use the code <?php foreach ($status->players as $player) { echo $player.'<br />'; } ?>, but it didn't yield the desired results. Any ...