Tips for parsing a string object in JSON without a preceding double quote

I'm working with an array in my Angular application, for example:

searchTerm : any[]

In the context of a textbox value like {'state':'tn'}, I'd like to push this to the searchTerm array. Currently, I achieve this by adding the item to a service and then the array as follows:

  private onItemAdded(event): void {
    const filter = JSON.parse('"' + event['value'] + '"');
    this.dataService.addFilter(filter);
  }

However, the stored result is "{'state':'tn'}"

How can I parse this without having double quotes at the beginning?

console.log('ADDED FILTER', event['value']);

The printed value here is {'state':'value'}

But when assigned to a variable as below, it ends up with added double quotes:

let filter = event['value'];

Thank you.

Answer №1

Instead of using the parse method, consider using stringify to convert your object to JSON format as a string. This will provide the desired result without the need for parsing.

const obj = "{'state':'tn'}";
let filter = JSON.stringify(obj);
filter = filter.slice(1, filter.length - 1);
console.log(filter);

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

Tips for maintaining the active state of a router link even when its parent route is activated

I have a navigation menu with 4 different sections: Home Categories HowItWorks About When the user selects "Categories," my URL changes to /categories/section1. In the section1 component, there are 2 buttons that lead to categories/section2 and categori ...

Exploring the Power of JSON in HighCharts

For creating the series, I am utilizing a ViewModel in the following manner: namespace AESSmart.ViewModels { public class HighChartsPoint { public double x { set; get; } public double y { set; get; } public string color { set; get; } p ...

Using Typescript with Gulp 4 and browser-sync is a powerful combination for front-end development

Could use some assistance with setting up my ts-project. Appreciate any help in advance. Have looked around for a solution in the gulpfile.ts but haven't found one yet. //- package.json { "name": "cdd", "version": "1.0.0", "description": "" ...

Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Adding a class dynamically to a <span> based on the value of a field or property

Learning Angular is still new for me, so please be patient. I have a TagComponent that includes a Color-enum and one of those colors as a property. I want Angular to automatically assign this color as a class so that Semantic UI can style it accordingly. ...

``Are you experiencing trouble with form fields not being marked as dirty when submitting? This issue can be solved with React-H

Hey there, team! Our usual practice is to validate the input when a user touches it and display an error message. However, when the user clicks submit, all fields should be marked as dirty and any error messages should be visible. Unfortunately, this isn&a ...

Getting unique identifiers for documents in AngularFire2's Firestore collections

After reviewing the Angularfirestores documentation, I found that it was not well documented. I encountered an issue while trying to retrieve unique IDs for each document from my Firestore database. Below is the code snippet I am working with: private bus ...

List the specific items in JSON format

I am looking to convert my list items into JSON format, rather than just printing out the values directly. Here are my list items: ans = "{ct} {p} {v} {f}".format(ct=item['COUNTRY'], p=totalPrice,v= item['VARIABLE_COST'],f=i ...

Troubleshooting Vue and Typescript: Understanding why my computed property is not refreshing the view

I'm struggling to understand why my computed property isn't updating the view as expected. The computed property is meant to calculate the total price of my items by combining their individual prices, but it's only showing me the initial pri ...

The Angular 6 service is not being invoked as expected, as it is not appearing in the network requests either

I am facing an issue with my Angular 6 application while trying to utilize a GET service to retrieve IP information from the server. Despite my various attempts, the GET service is not being executed and does not appear in the network calls either. Below ...

Instructions for transferring an Angular / Node.js application to a different computer

Hey there! I'm in the process of transferring my project to a new computer. Just to let you know, I've already set up node.js and mongoDB on the new machine. When it comes to the Angular app, I understand that I need to copy over the frontEnd d ...

Storing a JSON object within a data attribute in HTML using jQuery

In my HTML tag, I am storing data using the data- method like this: <td><"button class='delete' data-imagename='"+results[i].name+"'>Delete"</button></td> When retrieving the data in a callback, I use: $(this) ...

Error 34 on Twitter: "Apologies, but the requested page cannot be found" at: twitter.com/statuses/user_timeline/flecpoint.json?count=25

Some time ago, I developed a basic PHP script that reads Twitter status messages. It utilizes the twitter json feed found at https://twitter.com/statuses/user_timeline/flecpoint.json?count=25. The script fetches the timeline, stores it in a cache, and peri ...

utilize PHP for encoding JSON data in UTF-8

According to the php manual for json_encode(), which can be found at http://php.net/manual/en/function.json-encode.php, it states that all string data within the first input parameter value must be UTF-8 encoded. Does this requirement imply that the strin ...

ways to assign local file path as image url in json

Hey there, I am a new tool for angularjs. Take a look at the json file below: [ { "name": "WORLD", "population": 6916183000, "flagurl":"C:\xampp\htdocs\selva \Flag_of_the_People's_Republic_of_China.svg" }, { "na ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

What is the best method for eliminating the .vue extension in TypeScript imports within Vue.JS?

I recently created a project using vue-cli3 and decided to incorporate TypeScript for added type safety. Here is a snippet from my src/app.vue file: <template> <div id="app"> <hello-world msg="test"/> </div> </template& ...

Error with JSON parsing caused by commas in JSON file using JsonSlurper

When JSON data is received in my controller as params.formData, it has the following structure: '{"year":"2014","resource":["Smith, John","Foo, Bar"]}' Here's the code snippet I use to parse this data: .... def slurper = new JsonSlurper() ...

Issue with Angular FormControl Pattern Validator failing to validate against regex pattern

My goal is to restrict a text input field to specific characters only. I am looking to allow: alphanumeric characters (a-z A-Z 0-9) 3 special characters (comma, dash, single quotation mark) : , - ' A few accented characters: à â ç è é ê î ô ...