What is the best way to implement my function on every value in a JSON file?

I've got a JSON file that contains the following dataset:

[{
    "planet": "project pluto",
    "records": [
        {
            "project": "project pluto",
            "plan": "paper",
            "start": 1,
            "stop": 2
        }
    ]
},
{
    "planet": "project venus",
    "records": [
        {
            "project": "project venus",
            "plan": "rock",
            "start": 3,
            "stop": 4
        }
    ]
},    
{
    "planet": "project earth",
    "records": [
        {
            "project": "project earth",
            "plan": "scissors",
            "start": 5,
            "stop": 6
        }
    ]
} ]   

My desired output should look like this:

[{'planet': 'project pluto', 'records': [['project pluto', 'paper', 1, 2]]}, {'planet': 'project venus', 'records': [{'project venus','rock', 3,4}]}, {'planet': 'project earth', 'records': [{'project earth', 'scissors',5, 6}]}]

The code I currently have only works for the first part of the data, and fails to iterate over all other values:

import json

with open('planets.json', 'r') as f:
    data = json.loads(f.read())
data[0]['records'][0] = list(data[0]['records'][0].values())
print(data)

When I run the code above, the output is as follows:

[{'planet': 'project pluto', 'records': [['project pluto', 'paper', 1, 2]]}, {'planet': 'project venus', 'records': [{'project': 'project venus', 'plan': 'rock', 'start': 3, 'stop': 4}]}, {'planet': 'project earth', 'records': [{'project': 'project earth', 'plan': 'scissors', 'start': 5, 'stop': 6}]}]

Now, how can I iterate through and apply changes to all values in the JSON file?

Answer №1

If you wish to achieve this task, one way is to loop through the 'records' of each element in the data array.
Here's how it can be done with modifications directly on the original data:

import json
from pprint import pprint

with open('planets.json', 'r') as f:
    data = json.loads(f.read())

for obj in data:
    obj['records'] = list(obj['records'][0].values())

pprint(data, sort_dicts=False)

The resulting output will be:

[{'planet': 'project pluto', 'records': ['project pluto', 'paper', 1, 2]},
 {'planet': 'project venus', 'records': ['project venus', 'rock', 3, 4]},
 {'planet': 'project earth', 'records': ['project earth', 'scissors', 5, 6]}]

If preserving the original data array is important and you prefer not to modify it, here is an alternative approach:

from copy import deepcopy
import json
from pprint import pprint

with open('planets.json', 'r') as f:
    data = json.loads(f.read())

modified_data = []
for obj in data:
    new_obj = {key: deepcopy(value) for key, value in obj.items() if key != 'records'}
    new_obj['records'] = [deepcopy(value) for value in obj['records'][0].values()]
    modified_data.append(new_obj)

pprint(modified_data, sort_dicts=False)

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

convert a JSON object to an array using jQuery

Can anyone help me with converting an object into an array using jQuery? [["20"],["30"],["45"],["54"],["33"],["15"],["54"],["41"]] I am looking to achieve an array output like this: [20,30,45,54,33,15,54,41] Any suggestions on how to accomplish this? ...

Issue with accessing data from database in my app

I am currently working on a project that involves retrieving data from my database. The user inputs a car registration number and a rating (ranging from 1 to 5) and then clicks a button. Upon clicking the button, my code is supposed to execute, fetching te ...

What is the process for choosing a specific id from a JSON structure?

Is there a way to extract specific data from a JSON format within an Ionic project? What is the process for selecting the ID associated with particular data in a JSON format? And how can I retrieve and display the value linked to the selected product&apos ...

Finding the Index of Parsed JSON Data in Swift

I'm struggling with creating a loop to check if an employee can perform a specific service. It seems that the code I wrote for accessing the employee's services is not working. The employee data is loaded as JSON into EmployeesData. I believe I n ...

PHP Webservice is failing to return the encoded response accurately

A piece of PHP code that I developed successfully registers user details from my iPhone app and returns JSON output. Here is the code snippet: header('Content-type: application/json'); include 'connection.php'; $response = array(); $u ...

Difficulty encountered while extracting information from JSON output

I am new to working with JSON. The more I work with it, the more I find myself liking it. Currently, I have an output that resembles the following structure: [ { "product": { "id": "6", "category": "Books", ...

Scouring the web of URLs for each request utilizing Scrapy

Currently, I am facing a challenge in storing the trail of URLs that my Spider visits whenever it accesses the target page. The issue lies in reading the starting URL and ending URL for each request. Despite going through the documentation thoroughly, I fi ...

How to access objects in Angular2 without using pipe or ngFor

Suppose I have the following data in an asymmetric array: [{'name':'user','password':'123'},{'title':'officer','grade':'5','age':'5'}] which is obtained f ...

Python3 requires a bytes-like object to be encoded in Base64

Here is the code snippet: _cmd = "|| echo " + base64.b64encode(args.cmd) + "|base64 -d|bash" p.update({"form_284": _cmd}) The error encountered is as follows: Traceback (most recent call last): File "openemr_rce.py& ...

Improving efficiency of lengthy conditional statements in Python

I am working on a loop with an if statement that assigns a specific country name to a variable based on certain conditions. These conditions involve checking if the parameter contains the country name within a list of paths. The paths can vary with the co ...

Carry on executing Python Selenium script even after manually solving Captcha

As I am trying to register numerous individuals in a company's system, I encounter a captcha on the login screen. Before proceeding with automatically populating the data into the system, I prefer solving the captcha manually. Is there a method for th ...

Working with JSON Strings using moshi and retrofit2

The API I am currently utilizing responds with a JSON object nested inside a list structure: [ { "name": "Seattle", "lat": 47.6038321, "lon": -122.3300624, "country": &qu ...

Tips for narrowing down a sqlalchemy query based on a specific field within the most recent child entry

My current database structure consists of two tables that are roughly described in SQLAlchemy mapping as follows: class Parent(Base): __tablename__ = "parent" parent_id = Column(Integer, primary_key=True) class Child(Base): __tablename__ = " ...

Using unique headers with Phantomjs in Selenium WebDriver

As per the information provided here, it is now feasible to modify headers. Currently, I am attempting to adjust the Accept-Language in the PhantomJS webdriver. The code snippet below does not seem to be effective: DesiredCapabilities.PHANTOMJS['phan ...

What could be the reason for receiving empty content when using requests.get with the correct header?

While attempting to crawl a website, I copied the Request Headers information from Chrome directly. However, after using requests.get, the returned content is empty. Surprisingly, the header printed from requests is correct. Any idea why this might be happ ...

TarInfo objects dripping information

I've encountered an issue with my Python tool that reads through a tar.xz file and handles each individual file within it. The input file is 15MB compressed, expanding to 740MB when uncompressed. Unfortunately, on a particular server with limited mem ...

Discover the power of integrating JSON and HTTP Request in the Play Framework

My aim is to develop a methodology that can effectively manage JSON and HTTP requests. This approach will facilitate the transition to creating both a Webapp and a Mobile App in the future, as JSON handling is crucial for processing requests across differe ...

What is the best way to incorporate a search feature within Bootstrap cards?

I've been struggling to incorporate a search feature within my bootstrap cards. Despite trying various online methods, none have proven successful for me so far. Below is my HTML code - any assistance in implementing a search filter into my app would ...

Perform an HTTP/1.1 GET call on an Android device

I'm currently in the process of making a request to an API. The API has certain requirements that must be adhered to: The Base URL for our API can be found at (make sure to note the version number 1 after the /) All requests to the API should be ma ...

Ways to extract a specific line of text from HTML code

Can someone help me extract a specific line from an HTML code using Python? For instance, in this website: The snippet of code is as follows: var episodes = [[8,54514],[7,54485],[6,54456],[5,54430],[4,54400],[3,54367],[2,54327],[1,54271]]; I am lookin ...