top of page

Search this site

59 results found with an empty search

  • Babel 101: Writing Future JavaScript, Today

    If you’ve spent any time in the JavaScript ecosystem, you’ve likely heard the name Babel come up again and again. It’s one of those tools that quietly powers a huge portion of the modern web, yet many developers use it without fully understanding what it does or why it matters. Let’s break it down in a clear, practical way. Babel is a JavaScript compiler - a tool that converts modern JavaScript code (ES6+ and beyond) into a version that older browsers or environments can understand. Why Do We Even Need Babel? JavaScript evolves quickly. New features - like arrow functions, classes, optional chaining, and async/await - make code cleaner and more powerful. But there’s a catch: Not all browsers support the latest JavaScript features. For example, older browsers (like Internet Explorer or outdated mobile browsers) don’t understand newer syntax. If you write modern JavaScript and run it there, your code may break. This is where Babel steps in. What Babel Actually Does Babel takes your modern JavaScript and transforms it into backward-compatible code. Example: Modern JavaScript (ES6+) const greet = (name) => `Hello, ${name}`; After Babel (ES5) var greet = function(name) { return "Hello, " + name; }; Same functionality—just rewritten in a way older browsers understand. How Babel Works (Behind the Scenes) Babel processes your code in three main steps: 1. Parsing Your code is converted into an Abstract Syntax Tree (AST), which is basically a structured representation of your code. 2. Transformation Babel applies plugins to modify the AST. These plugins define how the code should change. 3. Code Generation The transformed AST is converted back into JavaScript code. Key Concepts in Babel 1. Presets Presets are collections of plugins bundled together. The most common one: @babel/preset-env – Automatically converts modern JavaScript based on target browsers. 2. Plugins Plugins allow you to transform specific features. Examples: Transform arrow functions Convert class syntax Support optional chaining 3. Polyfills Some JavaScript features (like Promise or Array.includes) can’t just be rewritten - they need actual implementations. Polyfills fill in those missing features. Real-World Use Case Imagine you're building a web app using modern syntax like: async/await Optional chaining (?.) Nullish coalescing (??) Without Babel, your app might break in older browsers. With Babel: Your code works everywhere You don’t have to worry about compatibility issues Babel in the Tooling Ecosystem Babel is rarely used alone. It integrates with many popular tools: Webpack - Uses Babel via babel-loader Vite - Uses Babel internally (or alternatives like esbuild) React - JSX is transformed using Babel Next.js - Comes with Babel configured out of the box Babel is one of the invisible heroes of modern web development. It allows developers to write cutting-edge JavaScript today while ensuring that their code still runs smoothly across a wide range of environments. If you're building anything for the web, chances are Babel is already part of your toolchain - even if you didn’t realize it. Understanding how it works gives you more control, better debugging skills, and the ability to optimize your build process when needed. In simple terms:👉 Babel lets you write tomorrow’s JavaScript and run it today. Want to know more check out the official website: - https://babeljs.io/

  • Getting Started with Gemma 4 in Google AI Studio

    Artifical Intelligence is getting interesting day by day as it continues to evolve rapidly, and Google’s Gemma family of models represents an exciting step forward in lightweight, efficient, and developer-friendly AI. With the release of Gemma 4, developers and researchers gain access to improved performance, better reasoning, and streamlined deployment options. Google - Gemma 4 Today, we’ll walk through what Gemma 4 is, how to set it up, and how to test it using Google AI Studio. What is Gemma 4? Gemma 4 is part of Google’s open model family designed to be: Lightweight and efficient compared to large proprietary models Optimized for developers who want flexibility and control Capable of strong reasoning and text generation tasks It is particularly useful for: Chatbots and conversational AI Content generation Code assistance Research prototyping Prerequisites Before getting started, make sure you have: A Google account Access to Google AI Studio Basic understanding of prompts and APIs Access Google AI Studio Go to Google AI Studio. Sign in with your Google account. Once logged in, you’ll see the dashboard with available models and prompt playground. Google AI Studio - Playground Select Gemma 4 Model Inside the AI Studio interface: Navigate to the Model Selection panel. Look for Gemma in the available models list. Select Gemma 4 26B A4B IT or Gemma 4 31B IT to start a new session. Google AI Studio - Model Selection You’ll now have access to a prompt editor where you can interact with the model directly. Basic Prompt Testing Start with simple prompts to understand the model’s behavior. Example Prompts: Explain quantum computing in simple terms. Write a Python function to reverse a string. Summarize the importance of climate change policies. Observe: Response accuracy Tone and clarity Speed of generation Google AI Studio - Gemma 4 Prompt Testing Adjust Parameters Google AI Studio allows you to tweak model behavior: Temperature: Controls randomness (lower = more deterministic) Thinking level: Model thinking Output length: Maximum length of token response Top-K / Top-P (Additional Settings): Controls diversity of output Structured Testing To properly evaluate Gemma 4, test across multiple scenarios: 1. Reasoning Tasks Prompt: “If a train travels 60 km/h for 2 hours, how far does it go?” 2. Coding Tasks Prompt: “Write a REST API in Node.js using Express.” 3. Creative Writing Prompt: “Write a short sci-fi story about time travel.” 4. Instruction Following Prompt: “List 5 benefits of exercise in bullet points.” Evaluate: Accuracy Completeness Instruction adherence Debugging and Optimization If outputs are not as expected: Refine prompts (be more specific) Use system-style instructions Adjust temperature and token limits Break complex queries into smaller parts Best Practices Use clear and structured prompts Provide context when needed Test with edge cases Monitor latency and cost if scaling Gemma 4 offers a powerful yet accessible way to build AI-powered applications. With Google AI Studio, you can quickly experiment, iterate, and deploy solutions without heavy infrastructure setup. Whether you're a beginner exploring AI or a developer building production-ready systems, Gemma 4 provides the tools to move fast and innovate. The key to mastering Gemma 4 lies in prompt engineering and experimentation. Spend time testing different inputs, understanding model behavior, and refining your approach. Once you’re comfortable, you can integrate it into real-world applications like chatbots, automation tools, or intelligent assistants. Happy building!

  • How to Setup Google OAuth and Connect it to Auth0

    "Sign in with Google allows users to authenticate using their existing Google accounts, eliminating the need to create and manage new credentials." In modern applications, users expect seamless login experiences — and “Continue with Google” has become a standard. Instead of managing passwords, applications can delegate authentication to Google using OAuth. Google OAuth verifies user identity securely through a token-based flow, eliminating the need to handle sensitive credentials directly. However, setting it up correctly involves handling redirects, client credentials, and token exchange. In this guide, we’ll configure Google OAuth and integrate it with Auth0 to enable a smooth and secure login experience. Step 1: Create a Project in a Google Cloud Open Google Cloud Console Click on Create or select a project → New Project Enter a project name Click Create Google Cloud - New Project Step 2: Configure OAuth Consent Screen (First Time Only) This step appears only if you are creating an OAuth client for the first time in the project Google Cloud Console → Google Auth Platform Click Get Started Fill in the following details: App Information App Name User Support Email Audience Select External Contact Information Developer Email Finish Accept the policy Click Create This screen defines what users see when they log in with Google. Google requires this before issuing OAuth credentials Google Auth Platform - Project Configuration Step 3: Create OAuth Client Google Cloud Console → Google Auth Platform → Clients Navigate to Google Auth Platform → Clients Click Create Client Configure Client Application Type: Web Application Name: Your app name Authorised JavaScript origins: https:// Authorised redirect URIs: https:///login/callback Google Auth Platform - Create OAuth Client Id Step 4: Configure Google Social Login for Auth0 You can enable social authentication using Google. Auth0 Dashboard → Authentication → Social → google-oauth2 Open the Auth0 Dashboard. Navigate to Authentication → Social. Select google-oauth2. Add the following credentials: Client ID Client Secret Scroll to the bottom of the page. Enable Promote Connection to Domain Level. Click Save. Auth0 - Google Social Connection With this setup, your application can now authenticate users using Google OAuth, providing a seamless login experience without requiring users to create new credentials. By integrating Google OAuth with Auth0, you get the best of both worlds — a familiar login experience for users and a secure, managed authentication system for your application. https://www.chandanrajpurohit.in/post/how-to-setup-auth0-for-openai-apps-sdk-with-mcp

  • Resolving “Domain Already Linked” Error in Google Workspace

    Adding a domain to Google Workspace is usually straightforward—until it isn’t. Recently, we ran into a frustrating issue where our domain couldn’t be added because it was “already linked” to another Google Workspace account. This blog walks through what happened, what we tried, and how we eventually resolved it. The Problem While attempting to add our domain to Google Workspace, we encountered the error: “This domain is already in use with another Google Workspace account.” This was confusing because: We had full ownership of the domain There was no known active Google Workspace account using it No one in our organization had linked it previously (as far as we knew) Initial Investigation Before jumping to conclusions, we verified a few things: Confirmed domain ownership via our DNS provider (in our case, the domain was purchased and managed through Wix) Checked with internal teams to ensure no prior Workspace setup existed Verified that no active Google accounts were using emails from this domain Approach 1: Standard Fix Attempts Verifying Domain Ownership Again We attempted to re-verify the domain using a TXT record. However, verification failed because the domain was already tied to another account. Checking DNS Configuration Existing TXT records MX records Any legacy Google verification entries (Nothing clearly pointed to an active Workspace setup.) Approach 2: Google Workspace Domain Recovery This is where things started to move forward. Google provides a domain recovery process specifically for situations where: A domain is already associated with another Workspace account You no longer have admin access to that account Steps We Followed: Went to the Google Admin domain recovery page Entered our domain name Verified ownership via DNS (TXT record) Submitted the request for recovery What Happens Behind the Scenes? Google verifies that you own the domain They attempt to contact the current admin (if any) If no response is received within a defined timeframe, they release the domain The Waiting Period This part requires patience. Google mentioned it could take up to 3 days During this time, the domain remains locked Google Workspace Domain Recovery Final Outcome After a few days, we retried adding the domain—and it worked! No errors. No conflicts. The domain was finally available. We were able to: Add the domain successfully Configure MX records Start creating users and using Gmail Pro Tips Keep track of all services linked to your domain Document Workspace admin credentials securely Remove unused domain associations when decommissioning systems Always clean up DNS records during migrations Conclusion The “domain already linked” issue can feel like a dead end, but it’s solvable. By understanding the root cause and following Google’s recovery process, you can regain control of your domain without needing access to the original account. If you’re stuck in a similar situation, don’t panic—just verify ownership, initiate recovery, and give it time.

  • How to Setup Auth0 for OpenAI Apps SDK with MCP

    "Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Your team and organization can avoid the cost, time, and risk that come with building your own solution to authenticate and authorize users." — Auth0 In modern applications, implementing authentication securely can be complex. Instead of building login flows, token handling, and security mechanisms from scratch, developers, often rely on managed identity platforms like Auth0. In this guide, we will configure Auth0 to work with an application built using the OpenAI Apps SDK and the Model Context Protocol (MCP). This setup will allow ChatGPT apps to authenticate users through OAuth before accessing MCP endpoints. Step 1: Create an API in Auth0 First, we need to create an API in Auth0. This API represents the backend resource that clients will request access to. Auth0 Dashboard → Applications → APIs → Create API Open the Auth0 Dashboard. Navigate to Applications → APIs. Click Create API. Enter the following details: Name: Your API name Identifier: https:// JWT Profile: Auth0 Signing Algorithm: RS256 User Access: Allow Click Create. The Identifier acts as the audience for your API and will be used later in the backend configuration. Auth0 - Create Custom API Step 2: Configure the Default Audience Next, configure a default audience so Auth0 automatically issues tokens for your API. Auth0 Dashboard → Settings → General → API Authorization Settings → Default Audience Open the Auth0 Dashboard. Navigate to Settings → General. Scroll to API Authorization Settings. Set Default Audience to: Click Save Changes. This ensures that when authentication occurs, Auth0 issues an unencrypted RS256 JWT token. Auth0 - Default Audience Step 3: Enable OIDC Dynamic Client Registration Apps built with the OpenAI Apps SDK dynamically register OAuth clients when connecting to an authentication provider. To support this behavior, OIDC Dynamic Client Registration must be enabled. Auth0 Dashboard → Settings → Advanced → Settings Open the Auth0 Dashboard. Navigate to Settings → Advanced → Settings. Enable OIDC Dynamic Application Registration. Click Save Changes. This allows external applications to dynamically register OAuth clients within your Auth0 tenant. Auth0 - Dynamic Client Registration Step 4: Configure Authentication Connections Auth0 requires at least one authentication connection so users can log in. Enable Username–Password Authentication Auth0 Dashboard → Authentication → Database → Username-Password-Authentication Open the Auth0 Dashboard. Navigate to Authentication → Database. Select Username-Password-Authentication. Enable Promote Connection to Domain Level. Save the changes. This allows the authentication connection to be used across applications within the Auth0 tenant. Auth0 - Promote Connection to Domain Level Step 5: Create an App in ChatGPT To connect your MCP server with ChatGPT, you must create an app in the ChatGPT developer interface. Enable Developer Mode ChatGPT → Settings → Advanced → Developer Mode Open ChatGPT. Click your profile icon. Go to Settings. Navigate to Advanced. Turn Developer Mode ON. Refresh the page. ChatGPT - Developer Mode Create the App ChatGPT → Settings → Apps → Create App Open Settings → Apps. Click Create App. Enter the following details: App Name: Your application name Description: Short description of what your MCP server does App URL: https:///mcp The App URL must: Be publicly accessible Use HTTPS Be reachable from the internet ChatGPT - New App Step 6: Backend Environment Variables Finally, configure the required environment variables in your Model Context Protocol server. AUTH0_DOMAIN=.us.auth0.com/ AUTH0_RESOURCE_SERVER_URL=https:// These values must match exactly with the configuration defined in Auth0. Troubleshooting Error: No connections enabled for the client Check the database connection settings. Auth0 Dashboard → Authentication → Database → Username-Password-Authentication Ensure Promote Connection to Domain Level is enabled. Error: Client is not authorized to access resource server Check whether the API is authorized for the application. Auth0 Dashboard → Applications → Applications → Select Application → APIs Make sure the API is authorized for the client application like User Access should be authorized. You can also inspect detailed logs at: Auth0 Dashboard → Monitoring → Logs With this setup, Auth0 now manages authentication for your OpenAI Apps SDK app connected to an Model Context Protocol server, ensuring that only authenticated users can access MCP resources. https://www.chandanrajpurohit.in/post/how-to-setup-google-oauth-and-connect-it-to-auth0

  • How to Submit Sitemap on Google Search Console and Bing Webmaster Tools

    What is a Sitemap? A sitemap is a file that lists all the important pages of your website. It helps search engines discover and crawl your content more efficiently. Most sitemaps are written in XML format and usually look like this: https://yourdomain.com/sitemap.xml Common sitemap URLs: /sitemap.xml /sitemap_index.xml /post-sitemap.xml Today, you'll learn how to: Submit Sitemap on Google Search Console Submit Sitemap on Bing Webmaster Tools To Submit Sitemap on Google Search Console Go to the Google Search Console and log in using your Google account. If you haven't added your website yet: Click Add Property Enter your website domain Verify ownership using one of Google's methods. Google Search Console - Overview After selecting your website property: Look at the left sidebar menu. Click on Sitemaps. This section allows you to submit and manage your website sitemap. Google Search Console - Add A New Sitemap In the Add a new sitemap field: Enter the sitemap URL. Example: sitemap.xml Click Submit. Google will now start processing your sitemap. Google Search Console - Sitemap Submitted Successfully To Submit Sitemap on Bing Webmaster Tools Go to the Bing Webmaster Tools and log in using your Google or Microsoft account. If you haven't added your website yet: Click Add a site Select one of the methods to add your site Import your sites from Google Search Console Add your site manually Verify ownership. After selecting your website property: Look at the left sidebar menu. Click on Sitemaps. This section allows you to submit and manage your website sitemap. Bing Webmaster Tools - Sitemaps Click on Submit sitemap: Enter the sitemap URL. Example: https://www.example.com/sitemap.xml Click Submit. Bing Webmaster Tools - Submit Sitemap Bing will now start processing your sitemap. Bing Webmaster Tools - Sitemap Submitted Successfully Congratulation 👏🏻 sitemap submitted successfully on Google Search Console and Bing Webmaster Tools. Benefits of Submitting a Sitemap Submitting a sitemap to Google Search Console and Bing Webmaster Tools helps you: Get pages indexed faster Improve website visibility on Google and Bing Search Help Google and Microsoft understand your website structure Track indexing issues Submitting your sitemap to Google Search Console and Bing Webmaster Tools is one of the simplest but most important steps in improving your website’s visibility in search engines. A sitemap helps search engines discover your pages faster, understand your site structure, and identify newly published or updated content more efficiently. While submitting a sitemap does not guarantee instant indexing or higher rankings, it significantly improves your website’s crawlability and technical SEO foundation. If you are using Wix, your sitemap is generated automatically, which makes the process much easier. Once submitted, you should regularly monitor: Indexing status Crawl errors Coverage reports Broken pages or redirects You can also use tools like URL Inspection in Google Search Console and Bing Webmaster Tools to manually request indexing for important pages and blog posts. After setting up your sitemap, consider reviewing other important SEO configurations such as: robots.txt ads.txt page indexing mobile optimization internal linking Keeping your technical SEO properly configured ensures that search engines can efficiently access and understand your content as your website grows.

  • How to Forward Your Custom Domain Email to Gmail Using Cloudflare

    If you own a domain and want a professional email address like contact@yourdomain.com, you don’t need a paid email hosting service to receive messages. Using Cloudflare Email Routing, you can forward emails from your custom domain directly to your Gmail account - all for free. This guide will walk you through setting up email forwarding, verifying your email, adding MX records, testing the setup, and creating a Gmail filter to keep your inbox organized. Step 1: Add Your Email in Cloudflare Log in to your Cloudflare dashboard and select your domain. Domains | Cloudflare Navigate to Email → Email Routing. Email Routing under Email | Cloudflare Click Get Started to enable email routing for your domain. Add your Gmail address as the destination address (the inbox where emails will arrive). Routing Rules in Email Routing | Cloudflare Create Custom Address (Email Routing) | Cloudflare Cloudflare will then send a verification email to confirm your ownership. Open your Gmail inbox and click the verification link. Created Routing Rule (Email Routing) | Cloudflare Make sure you check your Spam folder if the verification email doesn’t arrive in your inbox. Step 2: Add MX Records Suggested by Cloudflare After verifying your email, Cloudflare will suggest MX records to configure in your domain’s DNS settings. Note: - Please backup DNS Records to rollback. Log in to your domain registrar or DNS provider. Add the MX records exactly as Cloudflare specifies. Add the MX Record (Email Routing) | Cloudflare Remove any old MX records to avoid conflicts. Email Routing Status | Cloudflare These MX records tell the internet that Cloudflare will handle incoming emails for your domain. Step 3: Test Email Forwarding Once your MX records are live, send a test email from another account to: contact@yourdomain.com Check your Gmail inbox to confirm it arrives. Sometimes forwarded emails may land in your spam folder initially — don’t worry, this can be fixed with a Gmail filter. Step 4: Optional — Create a Gmail Filter for Organization To keep forwarded emails organized and prevent them from going to Spam: Open Gmail and go to Settings → Filters and Blocked Addresses → Create a new filter. In the To field, enter: contact@yourdomain.com Click Create filter. Choose Apply the label (e.g., Contact) and Never send it to Spam. Save the filter. Now all emails to your custom domain will appear under a dedicated label, making it easier to manage your inbox. Additional Note: Sending Emails from Your Domain Previously, Gmail allowed free accounts to “Send as” your custom domain. This feature has been disabled for free Gmail accounts. You can receive emails at Gmail through Cloudflare forwarding You cannot send emails from contact@yourdomain.com without a paid service, such as: Google Workspace ProtonMail Zoho Mail This limitation applies only to free Gmail accounts; upgrading to a paid plan restores full “Send as” functionality. Conclusion Using Cloudflare Email Routing with Gmail is a reliable and free way to receive emails from your custom domain. While sending as your domain is no longer available on free Gmail accounts, this setup is perfect for: Personal websites Portfolio contact forms Small projects or side businesses With proper Gmail filters, forwarded emails can be organized efficiently, keeping your inbox clean and professional.

  • Important Security Update for Next.js 15 & 16

    A critical vulnerability in React Server Components (CVE-2025-55182) has been responsibly disclosed. It affects React 19 and frameworks that use it, including Next.js (CVE-2025-66478). The issue is rated CVSS 10.0 and can allow remote code execution when processing attacker-controlled requests in unpatched environments. If you are using Next.js, every version between Next.js 15 and 16 is affected, and Vercel recommend immediately updating to the latest Next.js versions containing the appropriate fixes (15.0.5, 15.1.9, 15.2.6, 15.3.6, 15.4.8, 15.5.7, 16.0.7). Affected Next.js Versions Applications using React Server Components with the App Router are affected when running: Next.js 15.x Next.js 16.x Next.js 14.3.0-canary.77 and later canary releases Next.js 13.x, Next.js 14.x stable, Pages Router applications, and the Edge Runtime are not affected. Fixed Versions The vulnerability is fully resolved in the following patched Next.js releases: 15.0.5 15.1.9 15.2.6 15.3.6 15.4.8 15.5.7 15.6.0-canary.58 16.0.7 These versions include the hardened React Server Components implementation. If you are using another framework using Server Components, Vercel also recommend immediately updating to the latest React versions containing the appropriate fixes (19.0.1, 19.1.2, and 19.2.1). Upgrade Next.js now! To update to Next.js version 16, you can use the upgrade codemod: npx @next/codemod@canary upgrade latest The codemod is able to: Update next.config.js to use the new turbopack configuration Migrate from next lint to the ESLint CLI Migrate from deprecated middleware convention to proxy Remove unstable_ prefix from stabilized APIs Remove experimental_ppr Route Segment Config from pages and layouts If you prefer to do it manually, install the latest Next.js and React versions: npm install next@latest react@latest react-dom@latest or npm install next@15.0.5 # for 15.0.x npm install next@15.1.9 # for 15.1.x npm install next@15.2.6 # for 15.2.x npm install next@15.3.6 # for 15.3.x npm install next@15.4.8 # for 15.4.x npm install next@15.5.7 # for 15.5.x npm install next@16.0.7 # for 16.0.x You can read more about the vulnerability in our changelog. If you have any questions, please reach out to security@vercel.com.

  • Introduction To Terraform

    Terraform is an infrastructure as code (IaC) tool that helps us to build, change, and version infrastructure safely and efficiently. Terraform in simple words helps to provision the infrastructure. It helps automate and manage our infrastructure, our platform, and services that run on our platform. Terraform is an open-source project by HashiCorp. Terraform Architecture includes 3 main components. Terraform Core Terraform Config file (*.tf file) Terraform State file (*.tfstate) Terraform commands terraform init Terraform init initializes all modules we mentioned in the main.tf file. terraform plan Terraform plan check whether the execution plan for a configuration matches your expectations before provisioning or changing infrastructure. terraform apply Terraform apply command actually create the entire infrastructure based on changes terraform state file. terraform destroy Terraform destroy delete the entire infrastructure based on changes terraform state file. Note:- Terraform have the concept of Idempotency which makes sure that how many time we execute/apply terraform the infrastructure will remain same until the state is not changed.

  • Difference between json and jsonb in PostgreSQL

    PostgreSQL allows to store JSON data in json and jsonb datatype. Let’s understand the difference between json and jsonb. json jsonb json datatype was first introduced with Postgres 9.2. jsonb datatype was introduced in Postgres 9.4. json data type stores an exact copy of the input text. jsonb stores data in a decomposed binay format. json does not support indexing jsonb supports indexing [GIN (Generalized Inverted Index)] When to use json data type want to perform a lot of INSERT operations. no complex queries are expected on JSON data. you want to preserve the original JSON data indentation and format When to use jsonb data type want to store configuration data. data is highly nested data (the structure is expected to change over time). In general, jsonb is faster than json while accessing data but can be a bit slow while insertion. Additionally, for someone working in Django. Django ORM JSONField sets the datatype to jsonb by default in PostgreSQL. https://www.chandanrajpurohit.in/post/difference-between-json-dumps-and-json-loads

  • Difference between json.dumps() and json.loads()

    JSON is important for many backend devs. But sometimes playing with it can be confusing. Being a backend dev or full stack dev you might have written APIs for your Web or Mobile application and I’m sure you might have come across json.dumps() and json.loads(). Let’s understand the difference between json.dumps() and json.loads() with an example. json.dumps() import json user_details_dict = { "first_name": "Chandan", "last_name": "Rajpurohit" } user_details_string = """{ "first_name": "Chandan", "last_name": "Rajpurohit" }""" user_details_dict_json_dumps = json.dumps(user_details_dict) user_details_string_json_dumps = json.dumps(user_details_string) # user_details_dict_json_loads = json.loads(user_details_dict) # user_details_string_json_loads = json.loads(user_details_string) print(user_details_dict) print(type(user_details_dict)) print(user_details_string) print(type(user_details_string)) print(user_details_dict_json_dumps) print(type(user_details_dict_json_dumps)) print(user_details_string_json_dumps) print(type(user_details_string_json_dumps)) # print(user_details_dict_json_loads) # print(type(user_details_dict_json_loads)) # print(user_details_string_json_loads) # print(type(user_details_string_json_loads)) In the above code example, I have 2 objects one of a type dictionary and the other of a type string. json.dumps() returns a string for both dict and string objects, as you can see in the below response. {'first_name': 'Chandan', 'last_name': 'Rajpurohit'} { "first_name": "Chandan", "last_name": "Rajpurohit" } {"first_name": "Chandan", "last_name": "Rajpurohit"} "{\n \"first_name\": \"Chandan\",\n \"last_name\": \"Rajpurohit\"\n}" > So basically, json.dumps() serialize(or encode) and returns a Python object into a string formatted JSON object. In simple terms, it converts a Python object into a string-formatted JSON object. json.loads() import json user_details_dict = { "first_name": "Chandan", "last_name": "Rajpurohit" } user_details_string = """{ "first_name": "Chandan", "last_name": "Rajpurohit" }""" # user_details_dict_json_dumps = json.dumps(user_details_dict) # user_details_string_json_dumps = json.dumps(user_details_string) user_details_dict_json_loads = json.loads(user_details_dict) user_details_string_json_loads = json.loads(user_details_string) print(user_details_dict) print(type(user_details_dict)) print(user_details_string) print(type(user_details_string)) # print(user_details_dict_json_dumps) # print(type(user_details_dict_json_dumps)) # print(user_details_string_json_dumps) # print(type(user_details_string_json_dumps)) print(user_details_dict_json_loads) print(type(user_details_dict_json_loads)) print(user_details_string_json_loads) print(type(user_details_string_json_loads)) Now when I run the above code I get a TypeError: the JSON object must be str, bytes or bytearray, not dict. Traceback (most recent call last): File "", line 16, in File "/usr/local/lib/python3.11/json/__init__.py", line 339, in loads ERROR! raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict > Why this happened? Because json.loads() takes string-formatted JSON and as you can see in the above error it says that the JSON object must be str, bytes or bytearray, not a dict. import json user_details_dict = { "first_name": "Chandan", "last_name": "Rajpurohit" } user_details_string = """{ "first_name": "Chandan", "last_name": "Rajpurohit" }""" # user_details_dict_json_dumps = json.dumps(user_details_dict) # user_details_string_json_dumps = json.dumps(user_details_string) # user_details_dict_json_loads = json.loads(user_details_dict) user_details_string_json_loads = json.loads(user_details_string) print(user_details_dict) print(type(user_details_dict)) print(user_details_string) print(type(user_details_string)) # print(user_details_dict_json_dumps) # print(type(user_details_dict_json_dumps)) # print(user_details_string_json_dumps) # print(type(user_details_string_json_dumps)) # print(user_details_dict_json_loads) # print(type(user_details_dict_json_loads)) print(user_details_string_json_loads) print(type(user_details_string_json_loads)) So when I pass string-formatted JSON to json.loads I get a response which is of type dict. {'first_name': 'Chandan', 'last_name': 'Rajpurohit'} { "first_name": "Chandan", "last_name": "Rajpurohit" } {'first_name': 'Chandan', 'last_name': 'Rajpurohit'} > json.loads() deserialize(or decode) and returns a string-formatted JSON to a Python object. In simple terms, it converts string-formatted JSON to a Python object. In conclusion, when you want to convert string to dict use json.loads(), and when you want to convert dict to string use json.dumps(). Try the above code yourself and let me know your thoughts.

  • Introduction To LangChain

    2023 was all about AI. LLMs played a major role in speeding up the AI revolution but it is not ended yet the future holds a lot where machines can understand and generate language like never before and that to real-time. And according to me LangChain will play a major role in it. You all might be wondering what is LangChain? In simple terms, LangChain is a powerful tool which can help you build AI applications. LangChain was launched in October 2022, making it a relatively young but rapidly growing project in the field of Large Language Models and their applications. Using LangChain, you can build various applications that can interact with most of LLMs that are present in the market. Be it model from OpenAI or any open source model from Kaggle or Hugging Face. You can build amazing applications like A chatbot that answers your customers’ questions with human-like understanding. Write creative content like poems, scripts, or even code. Analyze code and data to find bugs or answer complex questions. Automate tedious tasks like summarizing documents or generating reports. Above are just beginner level project. You can create a lot complex AI usecases. So, what exciting possibilities does LangChain hold for 2024? Here are a few glimpses: AI-powered assistants like Jarvis: Not just Siri or Alexa, but assistants that truly understand your needs and goals, from planning your day to managing your finances. LangChain could become the brain behind the next generation of intelligent helpers. Breaking down language barriers: LanguageChain could translate languages seamlessly, breaking down communication barriers and fostering global understanding. Ready to explore it for yourself? If you are python expert head over to https://python.langchain.com/docs/get_started/introduction and start building your own linguistic adventures! If you are javascript or typescript expert head over to https://js.langchain.com/docs/get_started/introduction/ Know more at https://www.langchain.com

bottom of page