Converting data to a JSON string and then parsing it from a

I am encountering an issue when trying to stringify and parse a URL object.

To set the location in Angular's $location, I simply stringify my object like this:

 currentUrl = {"module1": {"is": true}}
 $location.search(JSON.stringify(currentUrl));

The URL parses correctly, but when I try to retrieve it from the URL, I get this back:

 console.log($location.search());
      ---
     Object {{"module1":{"is":true}}: true}

How can I convert this back into an object so that I can use it? When I try:

 JSON.parse($location.search());

I get a syntax error. Could this be due to how the search method returns the object? I'm a bit confused and could use some assistance. Thank you!

After setting it in the URL with:

 $location.search(JSON.stringify(currentUrl));

What steps should I take to return it to its original form:

 {"module1" : {"is" : true} }

Edit -

It seems that the JSON object is being set as the key in the location, like:

 { "mystrigifiedobject": true }

Edit2:

Following the first edit, I was able to resolve it (assuming it's set as the locations object key) like this:

  currentUrl = $location.search();
                    currentUrl = JSON.parse(Object.keys(currentUrl));
                    console.log(currentUrl);

This solution feels a bit odd. Am I doing something incorrect here?

Answer №1

The function `$location.search()` decodes the search items from the URL path and converts them into an object. For example, a URL like:

?a=b&c=d

will be transformed into this object:

{ a: 'b', c: 'd' }

By using the following code:

currentUrl = {"module1" : {"is" : true} }
 $location.search(JSON.stringify(currentUrl));

Your URL will appear as:

?%7B%22module1%22:%7B%22is%22:true%7D%7D

and the decoded object returned by $location.search will look like this:

{{"module1":{"is":true}}: true}

Note that this is an object with one entry where the key is your JSON data.

To retrieve your original object, you should do the following:

var parsedObject = $location.search();
var yourObject = JSON.parse(Object.keys(parsedObject)[0]);

You can also check out this jsfiddle for more details: http://jsfiddle.net/HB7LU/11633/

Remember to encode your string before placing it in a URL:

$location.search(encodeURIComponent(JSON.stringify(currentUrl))); 

Answer №2

$routeParams allows you to access both the values in routing templates and query strings (in string format).

function ctrl($routeParams) {
    var valueAsString = $routeParams.yourKey;
}

function ctrl2($location) {
    $location.search('yourKey', JSON.stringify(...));
}

An improved option is to transition to using UI Router, which handles this functionality more effectively.

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

Unable to run a query in PHP that executes successfully in phpMyAdmin

I'm currently attempting to remove rows from a table using the following code: $query = "Delete from usertour where tourID = $idnum and name LIKE '%$session%' "; However, even when the idnum and session are correct, the row is not being ...

I require the JSON data to be formatted in a visually appealing table style

I have a code snippet that is functioning perfectly. Here it is: import requests import xml.etree.ElementTree as ET import json def get_stock(sku): params = {'ItemId': sku} base_url = 'http://10.0.0.25/api/GetSku' respons ...

A guide on fetching JSON data into a Laravel controller

Among the plethora of inquiries scattered on StackOverflow, this particular one has caught my attention. I can vouch that I've exhaustively attempted all available solutions to no success. The predicament at hand involves transmitting JSON data from ...

Could not load ngx-restangular due to an error: (SystemJS) Module not yet loaded while trying to load "@angular/core"

Recently, I made the switch from using the AngularJS 'restangular' library to the Angular 'ngx-restangular' library during an upgrade from AngularJS to Angular. However, after the transition, I encountered an unexpected error along wit ...

Experiencing an unexpected abundance of console logs when implementing React Hooks

I am attempting to retrieve data from an API. The desired result is being obtained, but when I attempt to log it to the console, it logs 4 times. Within my app.js, I am utilizing the fetchData function: import React, {useEffect, useState} from 'rea ...

Show a random text value selected from an array

Here is what I am working with: let movie; const myMovies = ['Bones', 'Psych', 'Big Bang Theory', 'Mad Men', 'Breaking Bad', 'Modern Family', 'Game of Thrones', 'Dexter',&ap ...

Is it possible to trigger an action in Vue Store using a Window/onunload event?

Currently, I am working on integrating an event listener for the `unload` event to trigger a Vuex store action that will help identify the ID of the closing window. This is crucial in our application where we need to manage the number of open tabs due to r ...

Combining JSON objects using a LEFT JOIN in SQL Server based on a shared property

In my database, I have two tables. One table holds the schema (key, type) of a JSON object, and the other table holds instances of objects based on that schema. Sometimes, the object instance may not include all the properties defined in the JSON schema, ...

How to Examine Container for Volume Path in Docker?

After exploring the documentation, I've learned that I can retrieve information about my container's volumes by using the following command: docker inspect --format="{{.Volumes}}" container When executed, this command provides paths in the fol ...

Tips for successfully passing an entire object in the data of a datatable column property

I am currently using Datatables version 1.10.21 and implementing ajax with the column property to generate the datatables successfully. ajax: { url: dataUrl, //using dataUrl variable dataSrc: 'data' }, co ...

Creating an HTTP interceptor in Backbone: A step-by-step guide

After gaining experience with backbone, I decided to delve into learning angular. The features of angular really caught my interest, especially the HTTP interceptor. I began thinking about how to implement this functionality in backbone to display a spin ...

Is it possible to capture "global" events while handling nested iframes?

My dilemma involves capturing a keypress event, but the user can potentially be navigating through multiple layers of iframes nested within each other. Initially, I attempted to add the event listener to the document, only to realize that it wouldn't ...

Showing data retrieved from a JSON file on an Android device

Within my project, I have a json file stored in the raw folder that contains the following code (among other things): { "Monday": [ { "time": "09:15", "class": "Nature", "room": "AL32" }, { "time": "10:15", ...

Using Vue: Triggering .focus() on a button click

My journey with vue.js programming started just yesterday, and I'm facing a challenge in setting the focus on a textbox without using the conventional JavaScript method of document.getElementById('myTextBox').focus(). The scenario is that i ...

Is there a way to transform JSON text into a JSON object?

Similar Question: How do I convert JSON to a JavaScript object? { "data": [ { "name": "JoongBum Lee", "id": "526210623" }, { "name": "\uc774\uc778\uaddc", ...

Utilizing unique background images tailored to different screen resolutions

In order to enhance the user experience on my website, I am looking to implement a feature that dynamically changes the background images based on the user's screen resolution. My plan is to use a small snippet of JavaScript within the <head> s ...

Implementing Vuejs sorting feature post rendering

Currently, I have elements linked to @click event listeners. <th @click="sort('dateadded')" class="created_at">Date Added I am looking for a way to automatically trigger this sorting function when the Vue.js component renders, so that th ...

Use Staxon to transform JSON into XML format using Java

I am currently working on converting Json to XML utilizing the following code: public static String jsonToXML1(String source) { String xmlString = null; try { StringWriter stringWriter = new StringWriter(); InputStream inputStream ...

Dynamically loading an AngularJS controller

I am faced with the challenge of integrating an Angular app with dynamically loaded controllers into an existing webpage. Below is a code snippet where I have attempted to achieve this based on my understanding of the API and some research: // Create mod ...

Dynamic connections with Meteor and AngularJS

My publication relies on a specific parameter from the client, so when subscribing from the client side, I need to send this parameter to the server. I am utilizing the angular-meteor package and have come across the $subscribe wrapper. The syntax for usag ...