Analyzing a sizable JSON file serving as the data source for a PostgreSQL database

Currently, I am working on a Next.js project that involves a large JSON file (~65,000 lines) serving as data for a Prisma Postgres database. The structure of the file includes entries like the following:

[
  {
    "NativeClass": "class-name",
    "Classes": [
      {
        "key1": "val1",
        "key2": "val2",
        ...
      },
      {
        ...
      }
    ]
  },
  {
    "NativeClass": "class-name2",
    "Classes": [
    ...
  }
]

I specifically need the data from "Classes" only after certain "class names", while discarding the rest.

My inquiry has two components:

  1. What would be the most efficient approach to parsing the JSON file into SQL statements for populating the database?

As I am not well-versed in TypeScript, I have considered initially parsing the file in Python, but I am uncertain about inserting the data into the database afterwards.

Alternatively, I have contemplated utilizing the JSON.parse function in TypeScript, but I have encountered difficulties with it so far. I have attempted:

 // code snippet

However, I faced an error related to undefined values. I realize that when using a reviver, the inner children are transformed before the parent, making it challenging to determine when to extract the necessary data accurately. Is there a better method or am I misunderstanding how the parse function operates?

  1. The second aspect of my query pertains to the process of parsing this JSON file concerning future updates to the file.

This is a personal side project aimed at enhancing my web development skills as a college student majoring in Software Development. Therefore, I seek guidance on the best practices for handling such situations where the JSON file may occasionally require updating, prompting a re-evaluation of the JSON and subsequent database updates.

If my knowledge appears insufficient, I want to express my efforts in researching before seeking assistance on this matter. Any insights provided would be greatly appreciated.

Thank you for your support.

Answer №1

How about utilizing JSON functions in the following manner:

SELECT
    x ->> 'NativeClass' AS NativeClass,
    json_array_elements((x ->> 'Classes')::json) ->> 'key1' AS key1,
    json_array_elements((x ->> 'Classes')::json) ->> 'key2' AS key2
FROM
    json_array_elements('
[
  {
    "NativeClass": "foobar",
    "Classes": [ 
      {
        "key1": "val1",
        "key2": "val2"
      },
      {
        "key1": "val1",
        "key2": "val2"
      }
    ]
  },
  {
    "NativeClass": "xpto",
    "Classes" [ 
      {
        "key1"&: "val1",
        "key2" &: "val2"
      },
      {
        "key1": "val1",
        "key2":: "val2"
      }
    ]
  }
]') AS x

Result:

 nativeclass | key1 | key2 
-------------+------+------
 foobar      | val1 | val2
 foobar      | val1 | val2
 xpto        | val1 | val2
 xpto        | val1 | val2
(4 rows)

SQLFiddle

Answer №2

Let's start with a simple assumption: the Ingredients and Recipes types mentioned in your code may not be relevant to the current context.

If you're not very experienced with JSON, don't overcomplicate things. Here's a straightforward approach:

// Load and parse the file as shown in your sample code.
// Consider this example structure:

const json = [
  {
    "NativeClass": "class-name",
    "Classes": [
      {"key1": "val1", "key2": "val2"},
      {"key3": "val3", "key4": "val4"}
    ]
  },
  {
    "NativeClass": "class-name2",
    "Classes": [{"key5": "val5"}]
  }
];

// Filter records based on a specific value
const values = json
  .filter(item => item.NativeClass === "class-name")
  .flatMap(item => item.Classes);

console.log(values);
// ^ [{ key1: 'val1', key2: 'val2' }, { key3: 'val3', key4: 'val4' }]

// Insert these values into your database using Prisma:
const insertedRecords = await prisma.table.createMany({
  data: values,
});

This should cover the essentials.


Regarding updating the data as mentioned in your question, assuming it's for data seeding purposes, here's what I would suggest:

  1. Create an npm script:
"prisma": {
  "seed": "ts-node prisma/seed.ts"
}
  1. Delete old data and insert the updated data:
/* prisma/seed.ts */

await prisma.table.deleteMany();

// Parse the JSON...

// Insert the new data:
await prisma.table.createMany({
  data: values,
});

Check out Prisma's documentation on seeding for more detailed examples and information.

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

Issue encountered when attempting to call component function resulting in an exception with the message "is not a function"

I have developed a reusable function called emailValidator that allows me to use it across multiple areas of my application. In order to implement this function, I imported emailValidator into the file Contact.js and invoked the function like so: const ema ...

What might be the reason why the custom markers on the HERE map are not displaying in Angular?

I'm having trouble displaying custom icons on HERE maps. Despite not receiving any errors, the icons are not showing up as expected. I have created a demo at the following link for reference: https://stackblitz.com/edit/angular-ivy-zp8fy5?file=src%2Fa ...

Is there a way to specifically choose the initial element using Angular? "Backend powered by Django"

Hi there! I've set up Django on the back-end to send data to Angular, and I'm trying to display only the first comment from a list in my HTML page. However, when using limitTo, I encountered this error: Failed to compile. src/app/app.component. ...

The registration process with Next-auth using CredentialsProvider is experiencing some issues as the client is receiving a null Session

My GoogleProvider is functioning properly and returning a valid session. However, I'm encountering issues with the CredentialsProvider. The credentials provider successfully registers a user in the database using graphql. I am able to log the user in ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Switching "this" keyword from jQuery to TypeScript

A piece of code is functioning properly for me. Now, I aim to incorporate this code into a TypeScript application. While I prefer to continue using jQuery, I am unsure how to adjust the use of this to meet TypeScript requirements. if ($(this).width() < ...

Why is Next.js trying to connect to the database while initializing PrismaClient during the build process?

When attempting to build my nextjs application (npm run build), I noticed that the database is being requested during the build process on certain routes where I expect to dynamically query data. However, since the database is not available or live in my b ...

What is the best way to implement a sidebar closing animation?

Utilizing both react and tailwindcss, I successfully crafted a sidebar menu that elegantly appears from left to right when the user clicks on the hamburger icon. However, my attempts to create a reverse animation as the sidebar disappears from right to lef ...

Attempting to establish a connection with MongoDB through Realm

Exploring Realm and MongoDB for the first time has been an interesting journey for me. I began by following a helpful tutorial as a starting point for my project. Here is the link to my project structure on CodeSandbox The folder structure includes: src ...

Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure: <Col md="6"> <div className="hero-section"> <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}> <div className="front"> <div className="hero-section-content"> ...

Conceal the header on signup and login pages using Material UI

I am working on a project with three pages: SignUp, Login, and Lists, along with a header component. My goal is to hide the header on the SignUp and Login pages, and only show it on the List page. Any suggestions on how I can achieve this? Here is my cod ...

An error in TypeScript has occurred, stating that the type 'IterableIterator<any>' is neither an array type nor a string type

Hey there! I'm currently working on an Angular project and encountering an error in my VS Code. I'm a bit stuck on how to fix it. Type 'IterableIterator<any>' is not an array type or a string type. Use compiler option '- ...

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

What is the best way to attach several URLs to a single component?

I am currently using Next.js Here is the structure I have: https://i.stack.imgur.com/jRQBS.png I am in need of opening the same component for multiple URLs, such as 'http://localhost:3000/hakkimizda', 'http://localhost:3000/cerez-politika ...

Angular Error: Unable to access properties of null (specifically 'validators')

I am encountering an issue with my Angular code where I receive the error message "TypeError: Cannot read properties of null (reading '_rawValidators')". import { Component, OnInit } from '@angular/core'; import { Wifi } from './wi ...

Is there a way to authenticate the access_token from next-auth on an express node.js server?

I am currently in the process of learning about Next.js and I've encountered some difficulties when dealing with tokens. The issue at hand is that, to my understanding, I can utilize the access_token provided by a third-party service (like Google) as ...

RxJS: Understanding the issue of 'this' being undefined when used within the subscribe method

As I work on setting up a simple error notifications component and debug in Visual Studio, an issue arises within the subscribe function where 'this' is undefined. public notifications: NotificationMessage[]; constructor(notificationService: N ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Does a <Navigate> exist in the react-router-dom library?

Within the parent component import LoginPage from "pages/admin"; export function Home() { return <LoginPage />; } Inside the child component import { useRouter } from "next/router"; export default function LoginPage() { co ...