Extract information from a JSON string stored in a variable and transform it into objects within the $scope.variable

I currently have a string variable that contains JSON data displayed below.

var jsonstring = [{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"},
{"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"},
{"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]

My goal is to take this string and convert it into an array of objects (which will be stored in $scope.variable) so that I can access each object individually. I attempted to use JSON.parse(), but it ended up turning the entire string into one object instead of multiple objects.

Could someone assist me with this matter?

Answer №1

To properly read the full string, use JSON.parse.

Once parsed, each object within the array is accessible through regular array methods such as myArray[index], myArray.map(), or myArray.forEach().

Answer №2

[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"}, {"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"}, {"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]

This data represents an array of objects, not a string.

You could attempt the conversion again using this code snippet:

var jsonString = "[]"; var json = JSON.parse(jsonString);

Answer №3

let data = '[{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","application":"Phone","age":"< 1 Year"}, {"latitude":"27.58","longitude":"23.43","altitude":"","device":"Asc 140","rating":"4","region":"Africa","customer":"","time":"< 1 Week","error":"Error 1","application":"PCB","age":"1-3 Years"}, {"latitude":"39.55","longitude":"116.25","altitude":"","device":"CVB","rating":"4","region":"China","customer":"","time":"1-2 Weeks","error":"Error 2","application":"Sorting","age":"3-5 Years"}]';
$scope.dataParsed = JSON.parse(data);

Answer №4

The JSON.parse() function is used to parse a string as JSON data. The code you provided indicates an attempt to parse a JavaScript object instead of a string.

In the example below, an error occurs when trying to parse a JS object:

var jsonstring = [{},{}];
JSON.parse(jsonstring); // ERROR Uncaught SyntaxError: Unexpected token o

Instead, the following code should be used (note that jsonstring is now a string and not an object):

var jsonstring = '[{},{}]';
JSON.parse(jsonstring); // OK

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

AngularJS enables developers to make cross-domain requests using the $http service

Working on a simple AngularJS website that makes API calls for JSON data. Running into issues with Cross-Origin Resource Sharing (CORS) - any suggestions on how to handle cross-domain requests? Error: Issue: XMLHttpRequest cannot load . The 'Access ...

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Looping through a Map in JSP containing a nested List of lists of Strings

Looking to loop through a Map<String, List> in Java: final JSONObject mappedData = new JSONObject(); final Map<String, List<List<String>>> associatedUsecasesMap = new HashMap<String, List<List<String>>>(); // Code ...

Creating a versatile TailwindCSS grid that can adjust to varying numbers of grid columns

I am currently working with Vue3 and TailwindCSS, attempting to create a grid using a dynamic grid-cols-{n} class. While I am aware that TailwindCSS typically supports up to 12 columns by default, the challenge arises when the number of columns needed is e ...

Guide for setting up multiple checkbox event listeners with jQuery

I currently have 2 checkboxes on my form: <form action=""> <input id="bikeCheckbox" type="checkbox" name="bikeCheckbox" value="Bike">I own a bike<br> <input id="carCheckbox" type="checkbox" name="carCheckbox" value="Car">I ...

Capturing a part of the screen using JavaScript for screen recording

I'm exploring the possibility of implementing a JavaScript screen recorder that captures a video feed rather than the entire screen. I'm wondering if it's achievable using getDisplayMedia or if there's a specific library for this purpos ...

Fixing the mobile display issue with react-responsive-carousel

I am relatively new to ReactJS and I am looking to develop a responsive Carousel. Here is the code snippet that I have currently: To achieve a responsive Carousel for both desktop and mobile devices, I utilized the react-responsive-carousel library. The ...

How do I collapse the sidebar in mobile and tablet view using Bootstrap 4?

I am trying to create a collapsible sidebar that expands on large screens such as lg, but collapses with a visible button for tablet and mobile views (md or smaller). How can I achieve this responsive behavior for my sidebar on mobile and tablet views? It ...

JSON manipulation: Snowflake flattening with dynamic key changes

I am facing an issue with a table in Snowflake that has a similar structure to the one shown below, ---------------------------------------- Name | Number ---------------------------------------- Dim_1 | {'Table_1': 100} Dim_1 | {'Table_1&a ...

Close to completing the AngularJS filter using an array of strings

I'm currently working on developing a customized angular filter that will be based on an array of strings. For instance: $scope.idArray = ['1195986','1195987','1195988'] The data that I aim to filter is structured as fo ...

What is the process for generating an HTTP response that results in a pipe error being thrown

In my NestJS application, I have created a custom pipe that validates if a given value is a valid URL. If the URL is invalid, an error is thrown. This pipe is utilized in a controller to save an item into the database. Recently, I discovered that the pipe ...

Navigating between applications

Does anyone have suggestions on setting up routing between different apps without disrupting existing code? We want to make the integration process easy when adding a new app to our main application. For example, navigating from an electronics(main app) ...

Tips for showcasing the latest Google Map InfoWindows above previous ones

I have a dynamic Google Map with InfoWindows being added dynamically, but I am facing an issue where overlapping InfoWindows do not always display the most recent one on top of older ones. Is there a way to ensure that the latest InfoWindow always shows u ...

Display a smaller image preview in the product photo gallery

Hey there! I'm currently working on a website and looking to showcase my product in a similar way as shown here: I would like my main image to be displayed with all the other variants of the product image underneath, along with the same visual effect ...

Using the ternary operator in React to implement inline styles

Within my React/Typescript project, I aim to dynamically exhibit a color based on the presence or absence of a value in payload[1]. In the code snippet below, note the usage of an inline style tag. <li className="recharts-tooltip-item" style={ ...

What could be causing the "unsupported media type" error in Postman when sending a POST request in a Spring Boot application?

My entity class called State extends an abstract class named Location and implements its abstract methods. However, when I attempted to make a PostMapping request on Postman with the content type set to JSON, I encountered an error stating that it is an un ...

Combine the content from multiple text areas and submit it to another text area

****UPDATE**** Thanks to @JasonB, I was able to resolve the previous issue mentioned. Now, I have three additional textareas on the same form that should only appear when their respective checkboxes are clicked. How can I integrate this into my current sc ...

Utilizing Postgres JSON Operators in a WHERE Clause Using jOOQ

My database contains a JSONB column that stores arrays of strings, such as ["foo", "bar"] I am trying to write the equivalent jOOQ query for: SELECT * FROM sometable WHERE somecolumn ?| <mylist> ...where is meant to be linked to a Java List of st ...

Changing a JavaScript string into an array

I have extracted an array of objects from a hidden HTML input field and received the following string: "{"id":"1234","name":"john smith","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dab0a9b7b3aeb29ab8b6bbb2f4b9b5b7" ...

Is it possible to run unit tests for EcmaScript 6 (2015) code on a Headless Browser such as PhantomJS? If not, are there alternative methods to accomplish this task?

I'm currently conducting unit tests on an Angular application. I am facing difficulties executing unit tests for code written in ES6 using Chutzpah. Does anyone have a solution to this issue? I am looking for a reliable method to make this work. ...