Parsing clean data from intricate JSON structures in the R programming language

Utilizing the tidyjson package makes extracting neat data from a simple JSON effortless ()

However, when it comes to dealing with a more intricate nested JSON structure, applying this method becomes challenging. Specific questions like this one (how do you extract data from nested json data in R) are too limited in scope to be extrapolated to other situations.

A broader example can be found within this structure (view working reproducible examples here: 1.4 Example requests: )

{
        "data": {
          "type": "WIDGET TYPE",
          "id": "WIDGET_ID",
          "attributes": {
            "title": "WIDGET NAME",
            "last-update": "2019-02-01T08:26:34.000+01:00",
            "description": "WIDGET DESCRIPTION",
          },
          "meta": {
            "cache-control": {
              "cache": "HIT",
              "expireAt": "2019-03-01T17:18:22"
            }
          }
        },
        "included": [
          {
            "type": "INDICATOR_1 TYPE",
            "id": "INDICADOR_1_ID",
            "groupId": null,
            "attributes": {
              "title": "INDICADOR_1 NAME",
              "description": "INDICADOR_1 DESCRIPTION",
              "color": "#2fa688",
              "type": "INDICADOR_1 TYPE",
              "magnitude": "INDICADOR_1 MAGNITUDE",
              "composite": false,
              "last-update": "2019-02-19T08:26:34.000+01:00",
              "values": [
                {
                  "value": 12345,
                  "percentage": "VALUE BETWEEN 0 AND 1",
                  "datetime": "2019-02-04T20:44:00.000+01:00"
                }
              ]
            },
           {
            "type": "INDICATOR_2 TYPE",
            "id": "INDICADOR_1_ID",
            "groupId": null,
            "attributes": {
               …
            }
          }
        ]
       }
      }
  1. The primary level consists of an object "data" and an array "included"

  2. The array "included" contains one object for each indicator

  3. Within each of these objects lies an "attributes" object with a "values" array where the crucial data is stored: "value", "percentage", and "datetime"

The objective is to transform this data into a structured dataframe with columns "type", "title", "value", "percentage", and "datetime"

Answer №1

Through a series of trials and errors, I finally discovered the solution. I decided to share my findings here in case it may assist others working with the json object:

library(tidyjson)

json %>% # our json object
  enter_object(included) %>% # to enter the object containing the data
  gather_array() %>% spread_all() %>% # manipulating the array
  select(attributes.title) %>% # retaining this variable
  enter_object(values) %>&%gt; # accessing the array where the final data is stored
  gather_array() %>% spread_all() %>% # similar process for working with the array
  select(indicator = attributes.title, value, percentage, datetime) # selecting final data

The process essentially involves using

enter_object %>% gather_array %>% spread_all %>% select
twice. You simply need to specify the objects you wish to access at each level, as well as the information you want to extract.

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

Retrieving information from an ajax array in PHP

I am currently attempting to retrieve an array of data using AJAX on the PHP side, but I am facing difficulties in accessing the values in PHP. Here is my JavaScript code snippet: console.log(obj); $.ajax({ method: 'POST', url: '/in ...

Changing a Unique JSON Structure into a VB.NET Object

I have a JSON object that is structured as follows. { "Errors":{ "err1":[ //* Array of err1 objects ], "err2":[ //* Array of err2 objects ] } } This object is used to report errors identified in a request to a PHP page. My goal i ...

Retrieving various values with identical paths from JSON files using the JSON map feature in SAS

Could anyone assist me in extracting multiple values from a JSON with the same path using a JSON map? Any assistance would be greatly appreciated. Thank you. JSON { "totalCount": 2, "facets": {}, "content": [ [ { "name": "custo ...

Deciphering JSON information in RAILS 3.0.6 that is provided via an HTTP POST request using the content-type application/x-www-form-urlencoded

Upon receiving an HTTP POST from a third party with content-type specified as 'application/x-www-form-urlencoded' in my RAILS 3.0.6 controller, I attempted to parse the request in two ways: Firstly, by accessing the status parameter like so: job ...

Tips for dynamically creating column headings and table values using JSON arrays in AngularJS

On a web page, there are two radio buttons that produce different results: The first button shows Student Details and the corresponding JSON array is as follows : [{"Name":"A", "Class":"x", "Section":"abcd", "DOB": "XYZ"}, {"Name":"B", "Class":"x", "S ...

Transform pandas JSON data into a custom JSON structure using Python

Looking to Transform JSON Data in Python >>> print name_frame ... name name1 name2 name3 name4 Micro inc. NaN Jim D Susan A NaN NaN Vitacore Billy B NaN Sally Q Mark G NaN >> ...

Verify if the parsed JSON data is equal to NSNULL

I need assistance with parsing a JSON response and checking if one of my keys is null. Here is the code I am currently using: var routingNumber = (dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber") as! String When I run this cod ...

Displaying jsp variable in the browser console

When working in JSP, using <p>${ob}</p> to retrieve an object can be challenging due to the size of the object. Is there a way to utilize JavaScript to print it instead? Keep in mind that since this involves handling email content, JavaScript ...

Converting intricate JSON documents into .csv format

I have this JSON file containing a wealth of information about football players and I am trying to convert it into a .csv format. However, as a beginner in this field, I am facing some challenges! You can access the raw data file at: https://raw.githubuse ...

Would it be wise to store JSON files for my iPhone app on external servers?

Looking to enhance my app with "self-updating" features that refresh its content monthly. My current Squarespace website lacks file hosting capabilities, and I'm hesitant to invest in another domain just for a JSON file update. Are there any third-pa ...

Using Lua to access indices from a table that was generated from JSON data

Currently, I find myself in a situation where I have to use Lua to fetch weather data from the Openweathermap API. I've successfully sent an HTTP request to retrieve and save all the data, but now I'm facing a challenge with manipulating a deeply ...

AngularJs is being used to extract data from Firebase with the help of $value, $id, and

I have been working on retrieving data from Firebase in my HTML using AngularJS. Everything is functioning well, however, when I access the child node, the data is displayed in an unexpected format. Please refer to the images below for more details: This ...

Extract data from a DataFrame column using Spark Scala and convert it into an RDD with multiple columns

In my SparkScala RDD, the structure looks like this : df.printSchema() |-- stock._id: string (nullable = true) |-- stock.value: string (nullable = true) The second column of the RDD contains nested JSON data: [ { "warehouse" : "Type1" , "amount" : "0 ...

Is it possible to transform multiple input values into a JSON array using PHP?

I am working on a task to convert various input values into a JSON array using PHP. Here is the form structure: <input name="title[]"> <input name="description[]"> <input name="total[]"> This is the desired ...

Convert HTML code into a customized JSON structure

Is there a way to convert HTML into a specific JSON object? For instance This HTML page is well-structured (originally in markdown). I am interested in creating a JSON version of the different sections present on the page. In this scenario, every "h2" s ...

Using Python to Transform Nested JSON Data into an Unordered List in HTML

After conducting thorough research on Google, I was unable to find a suitable solution for converting arbitrarily nested JSON data into an unordered list format using HTML and Python. Ultimately, the problem was resolved with the help of a concise recursi ...

Using Java to implement an embedded document structure in MongoDB through REST APIs

I am currently developing a REST service in Java that utilizes MongoDB (specifically the `mongodb-java-driver`), Jersey, and Jackson. One of the classes I am working with is the Employee class. public class Employee extends BasicDBObject { public Empl ...

Issue with JSON data not functioning properly in AJAX request

I have been facing an issue with detecting whether a database entry has been successfully input. I am sending the new inserted ID and a JSON variable to an AJAX call, which works fine in all browsers but not in phonegAP. Despite that, the data is being suc ...

Setting parameters to Labels in Objective-C it is important to have unique

As someone new to iOS Programming, I have encountered an issue with assigning values to labels. Below is the data I receive from a service: ( { EmpName = Peter; Relation = SouthAfrica; }, { EmpName = Smith; Relation = WestIndies; }, { ...

The && symbol in JSONPath: combining conditions efficiently

Here is an example of JSON data taken from the tutorial: { "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", " ...