Trouble deciphering JSON data

The data below is what I have:

{
  "Result": "{\"Plot\":{\"Series\":[{\"color\":\"green\",\"title\":\"Temperature Gradient\",\"x_unit\":\"Temperature (°F)\",\"y_unit\":\"Depth (ft)\",\"dashStyle\":\"Solid\",\"lineType\":\"spline\",\"xAxisOnTop\":true,\"x_values\":\"80,90.78,101.56,112.35,123.13,133.91,144.69,155.47,166.26,177.04,199.96,210.63,220\",\"y_values\":\"0,-404.6,-809.2,-1213.8,-1618.4,-2023,-2427.6,-2832.2,-3236.8,-3641.4,-4046,-4502,-4825\"}]},\"OperatingTagResult\":null}",
  "StatusCode": 200
}

I am interested in creating two new variables based on the provided data.

  1. {\"Plot\":{\"Series\":[{\"color\":\"green\",\"title\":\"Temperature Gradient\",\"x_unit\":\"Temperature (°F)\",\"y_unit\":\"Depth (ft)\",\"dashStyle\":\"Solid\",\"lineType\":\"spline\",\"xAxisOnTop\":true,\"x_values\":\"80,90.78,101.56,112.35,123.13,133.91,144.69,155.47,166.26,177.04,199.96,210.63,220\",\"y_values\":\"0,-404.6,-809.2,-1213.8,-1618.4,-2023,-2427.6,-2832.2,-3236.8,-3641.4,-4046,-4502,-4825\"}]},\"OperatingTagResult\":null}

  2. Extract only the value 200 associated with "StatusCode"

How can I achieve this?

I encounter an error when trying to parse the JSON data:

Uncaught SyntaxError: Unexpected token o in JSON at position 1

Answer №1

To easily access the properties "Result" and "StatusCode", you can simply create a variable and use dot notation:

let earnings = {"Result":"{\"Report\":{\"Data\":[{\"type\":\"expense\",\"category\":\"Food\",\"amount\":50},{\"type\":\"income\",\"category\":\"Salary\",\"amount\":2000}]},\"SuccessIndicator\":true}","StatusCode":201}

let resultValue = earnings.Result; // {"Report":{"Data":[{"type":"expense", ...
let statusCodeValue = earnings.StatusCode; // 201

Answer №2

    var data = {
      "Info": "{\"Stats\":{\"Values\":[{\"color\":\"blue\",\"title\":\"Speed Data\",\"x_unit\":\"Time (s)\",\"y_unit\":\"Velocity (m/s)\",\"dashStyle\":\"Dashed\",\"lineType\":\"line\",\"xAxisOnTop\":false,\"x_values\":\"1,2,3,4,5,6,7,8,9,10,11,12\",\"y_values\":\"20,25,30,35,40,45,50,55,60,65,70,75\"}]},\"TagDataResult\":null}",
      "Code": 404
    };
    
    console.log(data.Info);
    console.log(data.Code);
    

There is no need to parse the json because it is already a jsonObject. Try parsing it with JSON.parse(jsonString) and retrieve the value to identify any existing errors.

Answer №3

To start, you must first declare a variable for your JSON data;

var Weather = {"Data":"{\"Forecast\":{\"Conditions\":[{\"color\":\"blue\",\"label\":\"Sunny\",\"temp_unit\":\"Fahrenheit\",\"depth_unit\":\"Feet\",\"style\":\"Solid\",\"type\":\"spline\",\"axisPosition\":true,\"x_values\":\"80,90.78,101.56,112.35,123.13,133.91,144.69,155.47,166.26,177.04,199.96,210.63,220\",\"y_values\":\"0,-404.6,-809.2,-1213.8,-1618.4,-2023,-2427.6,-2832.2,-3236.8,-3641.4,-4046,-4502,-4825\"}]},\"TagResult\":null}","Code":200}

then access the specific fields as needed:

var revenue = {"Data":"{\"Forecast\":{\"Conditions\":[{\"color\":\"blue\",\"label\":\"Sunny\",\"temp_unit\":\"Fahrenheit\",\"depth_unit\":\"Feet\",\"style\":\"Solid\",\"type\":\"spline\",\"axisPosition\":true,\"x_values\":\"80,90.78,101.56,112.35,123.13,133.91,144.69,155.47,166.26,177.04,199.96,210.63,220\",\"y_values\":\"0,-404.6,-809.2,-1213.8,-1618.4,-2023,-2427.6,-2832.2,-3236.8,-3641.4,-4046,-4502,-4825\"}]},\"TagResult\":null}","Code":200}

alert(Weather.Data);
alert(Weather.Code);

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

I'm struggling to retrieve $wpdb data after using a PHP function to load my posts with AJAX

Hey there! I'm trying to create a cool feature where users can view post archives grouped by year. When they click on a specific year, all the posts from that year should be displayed. I've set up an AJAX call to my functions.php file, which con ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Jersey 2.0 and Moxy Encounter Mysterious Internal Server Glitch with Silence in Server Log

After carefully following the Jersey 2.0 documentation (), updating the pom.xml file, adding the jersey-media-moxy artifact, compiling and installing everything correctly, I was able to successfully achieve basic POJO to JSON mapping for both Produces and ...

Generating multiple d3.js charts on a single page using various sections of the same JSON dataset

I have been on a thorough search to find the issue in my code, but sadly I haven't been able to identify it. Please forgive me if there's something obvious that I'm missing. The JSON object I am working with is structured like this: var da ...

How can I configure Grails to properly interpret my JSON PUT AJAX request?

In this Grails app, the form is set up in a standard way. <g:form url="[resource:myClass, action:'update']" method="PUT" > <fieldset class="form"> <g:render template="form"/> </fieldset> <fieldset c ...

Solving routing issues using object constructors in expressjs

Currently, I am in the early stages of developing an API REST using express and nodejs. As part of my routing process, I have decided to create separate "controllers" for each route and call these controllers within a router file. For example: ... router. ...

How to maintain global position, rotation, and scale when adding an object to a group in Three.js

I need to transfer an object from one group (or world/scene) to another group while maintaining its global transformation. I want the object to appear unchanged. Here is an example of what I am trying to achieve: //store the current world transformation ...

Maintain the CSS style of a parent element even when hovering over its child elements

I have successfully created a navigation bar with a menu that highlights a blue line whenever you hover over a section. However, I am facing an issue with the submenu within a section. I want the parent section to still display the blue line when hovering ...

What is the mechanism behind lazy module loading in typescript?

Exploring the concept of lazy loading in typescript, the author provides an example in this section of their book. They demonstrate it using the following piece of code: import bar = require('bar'); export function loadBar() { ...

Error Styling: Using CSS to Highlight Invalid Checkboxes within a Group

Is there a way to create a bordered red box around checkboxes that are required but not selected? Here is the code I currently have: <div class="fb-checkbox-group form-group field-checkbox-group-1500575975893"> <label for="checkbox-group-15005 ...

Guide on recreating Internet Explorer Basic authentication using Javascript

Currently, I am encountering an issue with logging into our web applications using JavaScript for Selenium test purposes. When accessing the app manually, Internet Explorer displays the authentication popup, requiring a username and password to access th ...

JavaScript Error: Attempting to access the "cart" property of an undefined session attribute

const express = require('express'); const router = express.Router(); const Cart = require('../models/cart') router.get('/', function(req, res, next) { const cart = new Cart(req.session.cart) }); Upon running the above node ...

What is the solution for resolving the "Duplicate key found" error in JSON-LD?

My Schema.org includes the following code for office hours, but it gives me an error when I test the URL using Google Structured Data Testing Tool. How can I resolve this error? Error: JSON-LD Duplicate key found. I have identified the issue: opens, c ...

Encountering an Error when Generating Facebook Website Audiences in JSON Format

I am currently working on a node.js script to generate Facebook audiences based on URL structure. However, I keep encountering the following error and cannot pinpoint what is wrong with the JSON data that I am sending: Error Received: FacebookRequestError ...

implementing firebase authentication with async/await

I have a basic Vue.js app that is currently authenticating existing users in Firebase using the `then` method. I would like to refactor my logic to use `async` and `await` instead. Can anyone provide guidance on how I can rewrite my code with `async` and ...

Next.js encountered an invalid src prop

Error: The src prop is invalid () on next/image, the hostname "scontent-atl3-2.xx.fbcd.net" has not been configured under images in your next.config.js For more information, visit: https://nextjs.org/docs/messages/next-image-unconfigured-host ...

Manipulating video volume using JavaScript injection

My web page includes a video, and I have successfully used JavaScript injection to control the play/pause functionality. Now, I am looking to also adjust the volume based on percentage. How can I create a function that decreases or increases the volume acc ...

You must pass a string, Buffer, ArrayBuffer, or Array as the first argument when using Uint8Array.slice(). A number was received instead

Here is my implementation of the ByteArray class, which extends the Uint8Array class. export class ByteArray extends Uint8Array { ... private _encoded: string; ... constructor(_encoded: string) { super(Buffer.from(_encoded, " ...

Ways to resolve the issue of the experimental syntax 'jsx' not being enabled

I encountered an issue while trying to implement react-fancybox and received an error. https://i.sstatic.net/vgFha.png To resolve the error, I executed the following commands: npm install --save-dev @babel/preset-react, npm install --save-dev @babel/plugi ...

Navigating within a class-based component using Next.js: A brief guide

Is it possible to create a redirect from within an onSubmit call while maintaining CampaignNew as a class-based component? I have provided the code snippet below, and I am looking for guidance on achieving this. import React, { Component } from "rea ...