Unable to display data retrieved from JSON file

I am encountering an unusual issue while trying to retrieve elements from JSON in JavaScript. I fetch a JSON string from a URL using the following code:

        // Create Request
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"www.someurl.com");

        // Create Client
        WebClient client = new WebClient();

        // Assign Credentials
        client.Credentials = new NetworkCredential("username", "pass");

        // Grab Data
        sjson = client.DownloadString(@"www.someurl.com");
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        oSerializer.MaxJsonLength = Int32.MaxValue;
        sjson = oSerializer.Serialize(sjson);

However, when I try to access the 'sjson' variable from JavaScript in my HTML code, it returns nothing. Interestingly, hardcoding the value works fine. Here is the JavaScript code snippet:

    <script type="text/javascript">
    var jsons = JSON.parse('<%=sjson%>');


    function initialize() {
        alert("hahahahaaa");
        document.writeln(jsons.Body[0].RowId.SensorIdValue);
        //document.writeln(myobject.Body[0].RowId.SensorIdValue);
    }
    </script>

The problem lies in this line of code:

    document.writeln(myobject.Body[0].RowId.SensorIdValue); 

It returns a value if I use the 'myobject' variable but returns nothing with the parsed 'jsons'. :(

Here is a sample output of the JSON response that I receive after running the serializer via C#.

If anyone can assist me with this issue, I would greatly appreciate it.

EDIT:

For further context, here is the raw JSON string obtained directly from the server without any serialization processes applied. Some contents have been omitted at the owner's request.

Answer №1

The data you're witnessing has been serialized twice in JSON format. First, it was converted to JSON on the remote server and then encoded again using JavaScriptSerializer. I discussed a similar scenario in one of my posts regarding ASMX ScriptServices, which provides more insights: http://example.com/json-serialization-mistake. While your situation may vary slightly, the outcome remains the same.

It's recommended to eliminate the JavaScriptSerializer code and simply return the original JSON string (sjson) without re-serializing it.

Answer №2

There is no need to utilize a Json serializer as the remote server already provides a JSON encoded string that can be directly used in your webpage, avoiding unnecessary double encoding.

Therefore:

public string FetchJson()
{
    // Set up WebClient
    using (WebClient client = new WebClient())
    {
        // Provide Credentials
        client.Credentials = new NetworkCredential("user123", "password456");

      // Retrieve Data
        return client.DownloadString(
            @"www.anotherurl.com"
        );
    }
}

and then:

<script type="text/javascript">
    var dataJson = <%= FetchJson() %>;
    function initPage() {
        alert("This is a message");
        document.writeln(dataJson.Body[0].RowId.Value);
        //document.writeln(myobject.Body[0].RowId.Value);
    }
</script>

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

How can I transfer checkbox data to another page utilizing ajax or javascript?

These are the checkboxes I am using and I want to pass the selected items' values to another page using ajax with javascript. I am looking to send the selected checkbox values through ajax to a different page... Your help would be greatly appreciate ...

What are some techniques for locating an element in Selenium when it has no tags?

I'm facing a challenge in my code where I need to ensure that the message "Product successfully added to your shopping cart" appears after adding an item to the cart. Here, there is no specific tag enclosing the text, making it tricky to target for ve ...

What is the process for renaming a Discord channel through nodeJS and discordJS?

I'm currently developing my first Discord bot using node.js and discord.js. My objective is to provide real-time information about a Minecraft server through Discord. What I aim to achieve is to have a channel that automatically updates its name per ...

Ways to direct to a specific div upon clicking an anchor tag following a page reload?

<a href="#goto">Link 1</a> <div id="goto">DIV</div> Whenever I click on the anchor tag, my webpage reloads and displays a new div with the ID of goto. This div was previously hidden but is now visible at the bottom of the page. I ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

Sorting an array of numbers using Javascript

Does anyone know how to properly sort an array in JavaScript? By default, the sort method doesn't work efficiently with numbers. For example: a = [1, 23, 100, 3] a.sort() The sorted values of 'a' end up being: [1, 100, 23, 3] If you hav ...

What is the method for retrieving information from a JSON file without using a key?

Currently, I am in the process of setting up a web server using Node.js and Express. As someone who is new to this, my goal is to retrieve data from a JSON file. For instance, consider the contents of my data.json file: [{ "color": "black", ...

Is it possible to asynchronously access a JSON object that has been retrieved from a local file on a global scale using the XMLHttpRequest method and

Having some trouble manipulating data from a local JSON file using this technique (no jQuery) as I can't seem to access the object on a global scale: var actual_JSON; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.o ...

Querying MySQL to retrieve JSON data associated with specific name-value pairs

Currently, my task involves working with a table where information is stored in JSON format within the table. The JSON value field appears as follows: To retrieve data from this table, I run the following SQL query: select * from k2_extra_fields where id ...

The React Bootstrap modal fails to display the value of an argument passed through a parameter

I am currently working on a project that utilizes React for its front end development. Below is the code snippet: import React, {useState} from 'react'; import Tree from 'react-d3-tree'; import { useCenteredTree } from "./helpers&q ...

How can objects be merged within an array and a new object be inserted?

I have an array of objects representing podcasts in a podcast app. Here is how the data looks: [{ id: "uuid-1" timeInSeconds: 1000 dateListened: "2021-01-01T15:57:17.000Z" }, // <---same day { id: "uuid-2" timeInS ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Tips for implementing a double loop on a JSON result

Here is the JSON result I'm working with: https://i.sstatic.net/ih4CH.jpg I am able to loop through the first level of the JSON data, but I am having trouble looping through the second level (SUBCATEGORIA). <ScrollView> {this.state.item ...

"Learn the process of transferring data from one controller to another in your application

After adding categoryCtrl and ProductCtrl, the code line: console.log(category); is functioning correctly. I am looking for a way to bind this data to the product controller using a for loop or any other method. .controller('CategoryCtrl', funct ...

Ensure the modal is closed when the user clicks on the Finish button within Docusign

I have a Docusign sign URL displayed in an iframe on my webpage. When the user clicks on FINISH, I want to close the modal iframe instead of redirecting to another page within the iframe. Please refer to the screenshot below for more clarity: I am implem ...

Loading Embedded Content with ReactJS

Currently, I am developing a one-page website with ReactJS. Each section of the site is created as individual React components, which are displayed conditionally based on the user's tab selection in the navigation bar. As part of my design, I have in ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

Passing the app variable from Express.js to routes

I am attempting to transfer some data from the app (variable defined as var app = express();) to some Socket.IO related code by sending a value to a middleware in a similar manner: function routes(app) { app.post('/evento', function (req, re ...

Organizing Firestore data into structured JSON format

For my database collection, I am utilizing a cloud function to download it as a JSON file. Here is the code snippet: exports.csvJsonReport = functions.https.onRequest((request, response) => { const db = admin.firestore() const userAnswers = db.col ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...