convert string to object from html input element - javascript

I have a textarea element which takes object types as an input
like
{
name: "root",
backlog: [
{name: "log#1"},
]
}
Accessing the data returns it as a string
Is there a simple way to convert the String to that specific javascript object without using regex filters? Just removing the outer quotation marks?

use json5 or Relaxed JSON library.
here is example using json5 library
let string = ` {
name: "root",
backlog: [
{name: "log#1"},
]
}`;
let object = JSON5.parse(string);
console.log(object)
<script src="https://unpkg.com/json5#^2.0.0/dist/index.min.js"></script>

To convert a string to a JSON, use: JSON.parse([the input]).
And, to convert it back to a string: JSON.stringify([the input]).

If i understand you correctly :
const string = '{ name: "root", backlog: [{name: "log#1"}]}'
const jsonStr = string.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});
const result = JSON.parse(jsonStr)
console.log(result)

If you want to use a simple, native approach you could simply stringify and then parse it using the intrinsic JSON object, i.e. something like this:
let yourObject = JSON.parse(JSON.stringify(textareaVariable));
This works because stringify will essentially format the string into a JSON string with the appropriate syntax for a JSON document, which you can then parse into a standard object.

Convert a JavaScript object into a string with JSON.stringify().
Create a JSON string from a JavaScript object.
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);
console.log(myJSON);
//Output: {"name":"John","age":30,"city":"New York"}
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
Creating an Object from a JSON String
const txt = {"name":"John", "age":30, "city":"New York"}
const obj = JSON.parse(txt);
console.log(obj.name + ", " + obj.age);
//Output:John, 30

You can simply use a JSON.parse call with some parameters to maintain the indetation.
const text = '{"firstName":"John", "lastName":"Doe", "address":{"city": "Tanger", "country": "Morocco"}}';
const obj = JSON.stringify(JSON.parse(text), null, 2)
console.log(obj);

Related

Add a field to a JSON object in javascript

How do you add a field to a json in javascript?
I've seen it done with arrays but I need it with a JSON field.
So basically
{
"hello":"this is cool"
}
into
{
"hello":"this is cool",
"hi":"i know"
}
You can do it like so
const json = {
"hello":"this is cool"
};
json['hi'] = "i know";
console.log(json);
If JSON is a string you can use JSON.parse() as per MDN web docs JSON.parse().
If you want to do it to JSON, then you can do it like below.
let json = `{
"key": "value"
}`;
const obj = JSON.parse(json);
obj.website = "Stack Overflow";
json = JSON.stringify(obj);
console.log(json);
However, if you want to do it to a regular object, just simply run the code below.
const obj = {
key: "value",
};
obj.website = "Stack Overflow";
console.log(obj);

How do you convert an object with duplicate keys to JSON/String?

Imagine you have an object like this:
var obj = {
name: "Mike",
name: "George",
age: 24,
}
Converting this to JSON with JSON.stringify(obj) yields:
{"name":"George","age":24}
This causes loss of data and isn't something we want.
Converting this to a string with toString() yields
[object Object]
, which isn't what we want either.
How does one go about this?
PS: I am aware that objects can't have two identical keys.
So after some brainstorming with the nice users that have commented here, a simple way to deal with this is to just turn it into a string manually. Like this:
var obj = `
name: "Mike",
name: "George",
age: 24,
`;
Then just parse it to your heart's content. For me personally, this could be a way to do it. However, this will obviously depend on the user-case.
var obj2 = {};
str = str.split(",").map(e => e.replace(/(\")/gi, "").trim());
str.forEach((e, i) => {
var temp = e.slice(0, e.indexOf(":"));
if(obj2[temp]) obj2[temp].push(e.slice(e.indexOf(":") + 1).trim());
else obj2[e.slice(0, e.indexOf(":"))] = [e.slice(e.indexOf(":") + 1).trim()];
})
The code above just splits the string based on some desired separator and processes the given array further. This might be a indelicate way to solve the question, but it works for my scenario :/. It yields the following JSON-object:
{"name":["Mike","George"],"age":["24"]}
Right after your object is defined, the second "name" key will override the first "name" key.
You can re-structure your object like this:
var obj = {
name: ["Mike","George"],
age: 24,
}
or
var arrayObj = [{
name: "Mike",
age: 24,
},{
name: "George",
age: 24,
}]
and use the built-in function for string in js to get your expected result.
Hope this helps!
You can't do it. the "name" value is the second value assigned to "name" key in javascript object or JSON. try to use obj.name it will be "George"
This is workaround to do what are you need.you can use "_" or any unused symbol.
const obj = {
name: 'ahmed',
_name: 'elmetwally',
title: 'js dev',
};
console.log(JSON.stringify(obj).replace(/\_/g, ''));
Here's a simple method to convert a string representation of the object into an array of key-value pairs.
It's not a general method, but it should work fine for an object with no nesting.
let result = document.getElementById('result');
let jsonStr = `{ name: "Mike", name: "George", age: 24 }`;
result.innerHTML = `jsonStr: "${jsonStr}"\n`;
// strip out '{}'
let jsonClean = jsonStr.replace(/{/g, '').replace(/}/g, '');
result.innerHTML += `jsonClean: "${jsonClean}"\n`;
// split jsonClean into array of key-value strings
let kvStrings = jsonClean.split(',');
result.innerHTML +=
`kvStrings: ${JSON.stringify(kvStrings)}\n`;
// form array of key-value pairs
let kvPairs = kvStrings.map(kvstr => {
let [key, value] = kvstr.split(':').map(el => el.trim());
// strip double quotes or convert to number
if (value.includes('"')) {
value = value.replace(/"/g, '');
} else {
value = Number.parseFloat(value);
}
return [key, value];
});
result.innerHTML += `kvPairs: ${JSON.stringify(kvPairs)}`;
<pre id="result"></pre>
So after some brainstorming with the nice users that have commented here, a simple way to deal with this is to just turn it into a string manually. Like this:
var obj = `
name: "Mike",
name: "George",
age: 24,
`;
Then just parse it to your heart's content. For me personally, this could be a way to do it. However, this will obviously depend on the user-case.
var obj2 = {};
str = str.split(",").map(e => e.replace(/(\")/gi, "").trim());
str.forEach((e, i) => {
var temp = e.slice(0, e.indexOf(":"));
if(obj2[temp]) obj2[temp].push(e.slice(e.indexOf(":") + 1).trim());
else obj2[e.slice(0, e.indexOf(":"))] = [e.slice(e.indexOf(":") + 1).trim()];
})
The code above just splits the string based on some desired separator and processes the given array further. This might be a indelicate way to solve the question, but it works for my scenario :/. It yields the following JSON-object:
{"name":["Mike","George"],"age":["24"]}

Parse a string into object?(JavaScript)

Would it be possible to parse a string as follows… {"Key": "Value"} back into a object? When I ever I try to parse it, I receive errors. I've been trying to use json.parse, but that does not work either.
This is what i have mapped out, but for this format it fails.
// Creating a list of objects, while mapping properties of an object
let obj = "{
"key": "3"
}";
let objList = Object.entries(obj).map(([key, value]) => Object.fromEntries(new Map([
[key, value]
])));
let obj = "{
"key": "3"
}";
This is incorrect: if you want to write a multiline string, you have to put a \ at the end of the line:
let obj = "{\
"key": "3"\
}";
But there is another error: you have to escape the ":
let obj ="{\
\"key\": \"3\"\
}";
You could use ' for enclosing string instead of " so you don't need the escape:
let obj = '{\
"key": "3"\
}';
Anyway this is a little string, you could write it in one line:
let obj = '{"key": "3"}';
Now you can use JSON.parse.
let obj = '{"key": "3"}';
console.log( JSON.parse(obj) );

Convert almost JSON string to JSON object Javascript

I have an string object like the following:
CustomData {
href: 'https://api.stormpath.com/v1/accounts/fdsq/customData',
createdAt: '2017-02-12T21:06:34.086Z',
modifiedAt: '2017-02-14T20:36:45.879Z',
ethereum_contract_address: '485dsq41g52fdsqqds',
ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736' }
I am trying to convert this string to a JSON object that I can then use properly. But i can't seem to convert this to a simple string that I could then substring and then parse to JSON.
Here is what i have attempted:
var rawString = req.user.customData;
console.log(rawString);
var stringJson = String(rawString).substring(0, 11);
console.log(stringJson.toString());
var customData = JSON.parse(stringJson);
console.log(customData);
I unfortunatly get stcuk on the JSON.parse, it seems like the string String(rawString) does not actually convert it to a string but only retruns [object Object].
You should use
JSON.stringify(jsonData);
then just simply parse
JSON.parse(jsonString)
You need JSON.stringigy(obj); to get a JSON-object of your data. Heres the code:
var customData = {
href: 'https://api.stormpath.com/v1/accounts/fdsq/customData',
createdAt: '2017-02-12T21:06:34.086Z',
modifiedAt: '2017-02-14T20:36:45.879Z',
ethereum_contract_address: '485dsq41g52fdsqqds',
ethereum_provider: 'proqxy53fdsq.yoicsfdsqfdsq.net:31gky6736'
}
console.log(customData);
var stringJson = JSON.stringify(customData);
console.log(stringJson);
var customData = JSON.parse(stringJson);
console.log(customData);
CustomData is a JSON: It contains keys and values. JSON stands for JavaScript Object Notation. You confuse JSON with JSON string. From the former you can achieve the latter via
var JSONString = JSON.stringify(CustomData);
You can parse it via
JSON.parse(JSONString);
However, since your object is already a JSON, you should be able to use it properly, whatever that means in your scenario.

Converting javascript dictionary to array/object to be passed in jquery.params

I have a javascript variable which is a dictionary of key-values pairs of querystring. I need to again convert this dictionary into a query string. I am using jquery.param functin but it takes either an array or an object. How can I convert my dictinoary variable to array/object which jquery.params can accept.
Tried using serializeArray but it does not work.
The jQuery.param method can take an array i in this form:
[{ name: 'asdf', value: '42' },{ name: 'qwerty', value: '1337' }]
If your dictionary have other property names, you can use the jQuery.map method to convert it. Example:
arr = $.map(arr, function(e){
return { name: e.key, value: e.val };
});
If I understand your question right (some code samples would help!) by "dictionary" you mean a construction like:
var dict = { key1: value1, key2: value2 … }
or:
var dict = {};
dict[key1] = value1;
dict[key2] = value2;
or possibly:
var dict = {};
dict.key1 = value1;
dict.key2 = value2;
If so, you should know that all of these are doing the same thing, i.e. setting properties on JavaScript objects, and should be serialised correctly by jQuery.param. Succinctly, JavaScript objects ≈ dictionaries.
use Object.values() :
var arr = Object.values(some_dict)

Categories

Resources