difficulty encountered while sending data to the API

I am facing an issue with my json file where I need to replace the value field with dynamic variables.
For example, if my app fetches "9.3", I want it to replace the existing value (2.3) in the json file.
I attempted using placeholders but encountered difficulties with this method:
JSON.stringify(jsonFile).split("{bloodGlucoseValue}").join(9.3)
This approach ended up corrupting my json file and prevented me from successfully POSTing it to my API due to a "Failed to parse request body as JSON resource...." error.

Is there another way for me to achieve this?

{
    "resourceType" : "Bundle",
    "type" : "transaction",
    "entry" : [
        {
            "fullUrl": "urn:uuid:patient",
            "resource" : {
                "resourceType" : "Patient",
                "name" : [
                    {
                        "given": ["ABC"],
                        "family": "Uni"
                    }
                        ]
                    },
                "request" : {
                    "method" : "POST",
                    "url" : "Patient"
                }
           },
        {
            "resource" : {
                "resourceType" : "Observation",
                "code" : {
                    "coding" : [
                        {
                            "system":"http://loinc.org",
                            "code":"15074-8",
                            "display":"Glucose [Moles/volume] in Blood"
                        }
                    ]
                },
                "subject": {
                    "type" : "Patient",
                    "reference" : "urn:uuid:patient"
                },
                "valueQuantity": {
                    "value": 2.3,
                    "unit": "mmol/l",
                    "system": "http://unitofmeasure.org",
                    "code": "mmol/L"
                }
            },
            "request" : {
                "method" : "POST"
            }
        }
    ]
}

Answer №1

One approach could be converting a JSON file into a JSON object to manipulate its values. Subsequently, you can convert it back to a string and save in a file or perform any other desired operation. Here's an illustration:

var jsonObject = JSON.parse(jsonFile);
jsonObject.entry[1].resource.valueQuantity.value = 9.3;
JSON.stringify(jsonObject);

Note that this is merely a demonstration. It is advisable to include checks to prevent potential exceptions.

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

Can multiple AJAX responses be received at the same time from the PHP server?

Looking to create a progress bar on my website to track the execution of a PHP script. The PHP script establishes connections with Google API, storing received data in the database. This process may take up to a minute at times. The PHP script is located ...

JavaScript does not seem to be functioning properly when loading data through ajax

I have created an image gallery using PHP and implemented a JavaScript code to create a CSS "overlay" effect when the image is clicked. <script type="text/javascript"> $(".button").click(function(e) { e.preventDefault(); $.ajax({ ...

Improved Method for Converting Archived Python Dictionaries to JSON

I have a large collection of historical data stored in Python dictionaries that I am currently converting to JSON format. I am looking for ways to streamline this process and I would appreciate any insights or suggestions from the community. Currently, my ...

Steps for implementing CSS styles following a specific tag

My HTML code includes a <div id="content">, with various elements within it: <div id="content"> <main> <h2 > Example Title</h2> <p>Hello World</p> <table class="table table-striped table-responsi ...

What are the steps to reset the Firebase server in order to allow the deployment of functions

After using firebase deploy --only functions, an error appeared in my React code and I had to use control-C to stop the deployment on my Mac. Now, when attempting to redeploy to Google servers, the following error is encountered: firebase.js -> build/f ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

use javascript to navigate back to the parent window

When I open a new child window from the parent window, there is an HTML form in the child window for user input. Once the form is filled and submitted, the request is sent to the server. I want the response from the server to be redirected back to the pa ...

Error: Unable to access 'map' property of an undefined variable in NextJS while using getStaticPaths

Currently facing an issue with dynamic routing in my Next.js project. I have a dynamic page [id].js and am trying to fetch data from an API. const res = await fetch(`myAPI`); const resData = await res.json(); const paths = resData.data.map((r) =&g ...

Extracting URLs from dynamic JavaScript page using BeautifulSoup and Selenium

Seeking to extract all URLs from a Git repository where any email addresses appear. Utilizing The script: from bs4 import BeautifulSoup from selenium import webdriver url = 'https://grep.app/search?current=100&q=%40gmail.com' chrome = " ...

Tips on properly updating a property of a state object in ReactJS using the useEffect hook for functionality

I have a snippet of code that initializes some data: const userData = useSelector(state => state.userData); // Get from redux state const [formData, setFormData] = useState({ userId : '', ...

Can a function be passed as props in a scenario where both a Parent and Child component are functional components?

I have a component called ParentComponent where I am trying to pass a function named toggleDrawer to another component called ChildComponent in the following way: const ParentComponent = () { const [drawerState, setDrawerState] = useState(false); ...

The import map is not being recognized by Supabase Edge Functions when passed in the command `npx supabase functions serve`

My situation involves two edge functions, namely create-payment-link and retrieve-payment-link. However, they are currently utilizing the import map located at /home/deno/flag_import_map.json, rather than the import_map.json file within the functions folde ...

Check the box to show the corresponding sections of the form

https://i.sstatic.net/oXw8K.png.If there are two checkboxes with options true or false, how should I handle a third checkbox? I want to display different parts of the form based on the selection of the checkboxes. ...

Unable to modify the color of the alert notification in JavaScript using React

I've been attempting to create an alert component, but I'm facing an issue with adjusting the color of the alert message. Upon enabling dark mode in the navbar (located at the bottom of the navbar component code), an alert message confirming the ...

Is it possible to conduct an auction in JavaScript without using the settimeout or setinterval functions?

I'm currently working on creating an auction site and I need help improving its speed and performance. I've been using setInterval and setTimeout functions for the countdown, but it's quite slow as a request is sent to the server every secon ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Creating a variety of NextJS components

Currently delving into NextJS and aiming to showcase a website featuring my various projects created with it. A special "Tag" component functions as a button template that allows custom text passed through props: export default function Tag({val}) { r ...

Deliver PDF to web browser through JSON with MVC3

Whenever an image is clicked, I need a PDF to open in the browser. To achieve this, I am using Jquery ajax POST call to communicate with ASP.NET MVC and receive a file in response. The POST method is necessary as it allows me to send significant data from ...

Troubleshooting: Ineffective use of replace() function on input value with jQuery

Visit this link for a demo How can I update the input value based on user selection in a dropdown menu? The objective is to change the value from "service_######" to "membership##_####" when the user selects YES, but my current JavaScript code using repla ...

JS seems to kick in only after a couple of page refreshes

I'm facing an issue with my 3 columns that should have equal heights. I've implemented some JavaScript to achieve this, which you can see in action through the DEMO link below. <script> $(document).foundation(); </script> <scri ...