How to convert string to object in javascript? - javascript

const str="{a:{url:'http://localhost:80',c:1,},d:'d',e:true}"
How to get the result without using evil and new Function:
const obj={a:{url:'http://localhost:80',c:1,},d:'d',e:true}

First of all:
You need to format your string into a valid JSON format ( double quotes instead of single quotes )
And then you'll just need to JSON.parse(str)

To convert a string to json you can use JSON.parse(str)
But first make sure the string syntax is correct, there are several websites to do this, one of many is this https://jsonlint.com/

Related

parse a string that contains array with strings

I am struggling to parse a string that contains array. And the array also contains list of arrays.
Each of the array contains string.
code here
let a = "[[48934, 'Danial Brendon', 'developer'],[48934, 'Nicki Lopez', 'developer']]";
console.log(JSON.parse(a))
I tried using JSON.parse() but did not work, may be because JSON.parse() also want to parse the string.
I am having difficulty with this even this looks simple. I could not find any similar question/answer like this.
Thanks.
To JSON parse , you need double quotes instead of single. like this ...
let a = '[[48934, "Danial Brendon", "developer"],[48934, "Nicki Lopez", "developer"]]';
console.log(JSON.parse(a));

Get the array in a string [javascript]

I need to get the array in the string below:
"['Comedian', 'Actor']"
For example, for the above, I should get ['Comedian', 'Actor'].
Already working using eval(). Is there any other way to get the desired result?
Normally i would suggest using a JSON.parse functionality to do so, however since this is not a valid json format due to single quotes instead of double quotes you could try to first replace those and only then parse
const str = "['Comedian','Actor']";
console.log(JSON.parse(str.replace(/'/g, '"')));
or you could use JSON5
const str = "['Comedian','Actor']";
console.log(JSON5.parse(str));
<script src="https://unpkg.com/json5#^2.0.0/dist/index.min.js"></script>

How to handle JSON string errors (error character ") in javascript

An administrator has directly filled content into the database and formatted it as json string. However, when retrieving it from the database and parse it into json, it failed. Because when filling data directly, instead of content need to write this (\"), they just write (") the json string shield is faulty and cannot parse. How to solve this problem.
Ex:
"aaaa"dddd"aaaa" => "aaaa\"dddd\"aaaa"
I assume that when you retrieve the string from the database, you are getting something like: '"aaaa"dddd"aaaa"'
If so, then you can convert that to a valid JSON string by removing the first and last double quotes and using JSON.stringify to convert the string to a valid JSON string (including escaping the inner double quotes).
For example:
const s = '"aaaa"dddd"aaaa"';
const escaped = JSON.stringify(s.slice(1, -1));
console.log(escaped);
// "aaaa\"dddd\"aaaa"
const parsed = JSON.parse(escaped);
console.log(parsed);
// aaaa"dddd"aaaa
You might use replace with RegExp and g flag
let str = `"aaaa"dddd"aaaa"`;
let result = str.replace(/"/g,`\\"`).slice(1,-2) + '"';
console.log(result)
OP asked My database return result string "aaaa"dddd"aaaa", How to assign such "aaaa"dddd"aaaa"
You can interpolate that return from database into Template Strings
let str = `${database.value}`;
Not sure what database or what language is on server side, however, rather that trying to escape the inner quotes. Trying just replacing the first and last double quote with with a single quote. Not sure of the full context here to know whether this is the issue. Anyway, something to consider

Convert String of certain format to JSON in javascript

I have a string of the format
var str = "{key1=value1, Key2=value2}"
I need to convert this into a json object to be able to iterate through it.
Any suggestions on how this can be done? there can be any number of keys
You need first to "JSONize" this string you are getting so it can be converted to a JavaScript object using the JSON class. My guess, if the string has always this format ({key=value, ...}), is that you could parse it first like this:
var parsedString = yourString.replace(/(\b\S+\b)=(\b\S+\b)/g, '"$1":"$2"')
This way, from this: "{key1=value1, Key2=value2}" you get this: '{"key1":"value1", "Key2":"value2"}'.
Then, as someone suggested, just use JSON.parse(parsedString) to get your JS object.

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

Categories

Resources