0

Problem 1: Can this be achieved in javascript?

value = "['iPhone', 'iBall']" 

to

value = ['iPhone', 'iBall']

Problem 2: To make it harder, The values are encoded:

value = "['iPhone', 'iball']"
4
  • Where is this data coming from? Can you get the data in a "proper" JSON format to begin with? Otherwise, you'll have to "convert" this to JSON. Commented Feb 16, 2021 at 19:47
  • I'm a django developer. so from backend im sending a list(array) and in forntend JS script i'm recieving it but its coming as encoded like i said in problem 2. Commented Feb 16, 2021 at 19:53
  • 2
    It sounds like you need to fix this on the back-end. You should be able to properly JSON encode the data so the front-end can easily parse it. Commented Feb 16, 2021 at 19:54
  • For any django developers this might help. just use {{ value|safe }} instead of '{{ value }}' do not include double or single quotes Commented Feb 17, 2021 at 11:46

1 Answer 1

2

Does this help ?

var value = "['iPhone', 'iBall']";
value = JSON.parse(value.replaceAll(`'`, `"`));
console.log(value);


value = "['iPhone', 'iball']";
value = JSON.parse(value.replaceAll(`'`, `"`));
console.log(value);
console.log(typeof(value));

Sign up to request clarification or add additional context in comments.

5 Comments

This will work for the text values given, but if there were any other special characters inside the values (&, for example) I suspect it would be encoded by the server as well. I think the right solution is to solve this in the back end and return valid JSON.
@Pranav Rustagi Yeah the answer works fine. But If you check the typeof value is still string.
Thanks for all. I solved my probelm with the help of this answer as well as few backend changes. Previously i was sending {'key': ['values']} Not working well. so added nested dict. {key: {key: ['values']}} worked. Even this approach got me an encoded response but after replacing it(above solution). it worked well.
@AndyMerts I don't think that there will be any problem with special characters as I'm using replaceAll() which will replace the occurrences of Apostrophe, both ( ' ), as well as encoded ('), with ` " `.
@jeevu94 the type of value was object (array), and not string. I just didn't assigned the object to value variable, and generated console directly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.