Parse a string into object?(JavaScript) - 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) );

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);

convert string to object from html input element

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);

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"]}

RegEx to find json values without quotes

I'm having an issue with a parser (in this case PowerBI) not taking values that are not quoted.
The example JSON file which comes from an API is validating ok, but PowerBI is not having any of it:
{'requester_id': 361114274894, 'submitter_id': 361114274894, 'assignee_id': 361282665913, 'organization_id': 360009532534, 'group_id': 360000498954, 'name':'John Doe'}
I'd like to find all values without quotes so I can replace them.
Please help.
It seems like you'd like to convert your int values to string.
var json = {'requester_id': 361114274894, 'submitter_id': 361114274894, 'assignee_id': 361282665913, 'organization_id': 360009532534, 'group_id': 360000498954, 'name':'John Doe'}
Object.keys(json).forEach(i => json[i]=json[i].toString());
// output
json
{
assignee_id:"361282665913"
group_id:"360000498954"
name:"John Doe"
organization_id:"360009532534"
requester_id:"361114274894"
submitter_id:"361114274894"
}
The issue is with the use of single quotes instead of double quotes around the property names.
let correctedInput = input.replace(/'/g, '"');
let parsedInput = JSON.parse(correctedInput);
parsedInput will now be your javascript object.
input.replace(/'/g, '"') will find and replace all ' characters, and replace them with " characters. This should work fine unless any of your property values have single quotes in them - For example, the name O'malley will be parsed incorrectly.
You can use the for in loop. Assuming all non string items are numbers the following will work.
const obj = {
a: 123,
b: "234234",
c: 09,
};
console.log(obj);
for (key in obj) {
obj[key] = obj[key] + "";
}
console.log(obj);
If the goal is to gather all the keys with non-string values rather than replacing them you can save them to an array and manipulate them later:
const obj = {
a: 123,
b: "234234",
c: 09,
};
const arr = [];
for (key in obj) {
if (typeof obj[key] !== "string") {
arr.push(key);
}
}
console.log(arr);
You can perform the regex pattern matching as below in Java
String rtype="^\"|\"$";
String value = ((JSONObject) nameOfObject).get("key").toString().matches(rtype);
or
((JSONObject) nameOfObject).get("key").toString().replaceAll(rtype);

Extract only values from JSON object in javascript without using a loop

is there a "Nice" way to get all the values out of a json object (I don't care about the keys) - just get the values into array,
without using a loop ?
(lang is Javascript)
It depends on how you define "loop".
You can extract the properties with Object.keys and then map them to their values.
… it's still essentially a loop under the hood though.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
console.log(values);
With weaker browser support you could use the values method.
var json = `{ "foo": 1, "bar": 2, "baz": 3 }`;
var obj = JSON.parse(json);
var values = Object.values(obj);
console.log(values);
I think you are looking for Object.values() function, just pass the object to the values method of Object as first param. That's it!
Object.values({something: 'lol'});
> ["lol"]
Recursively extract as text
Yes, this is a loop but the underlying methods you are calling such as Object.values or arr.map are still loops. I found this useful for extracting text out of a json object for full text search in particular and thought it useful as I came here initially needing this but the answers only touched the surface as json is recursive in nature.
function textFromJson(json) {
if (json === null || json === undefined) {
return '';
}
if (!Array.isArray(json) && !Object.getPrototypeOf(json).isPrototypeOf(Object)) {
return '' + json;
}
const obj = {};
for (const key of Object.keys(json)) {
obj[key] = textFromJson(json[key]);
}
return Object.values(obj).join(' ');
}
With ES2017 you have Object.values(). You can polyfill it also.
Only you need is transform JSON to JavaScript object and call Object.values(). The result is an array of values.
var obj = JSON.parse(jsonData);
var result = Object.values(obj);
If you pass a function to JSON.parse, it will be called each time a value is parsed:
function get_values(json) {
let values = []
JSON.parse(json, (key,value)=>{ values.push(value) })
return values
}
ex:
get_values(`{"a":1, "b":[true, false], "c":3}`)
// returns a list of:
• 1
• true
• false
• [true, false]
• 3
• {a:1, b:[true, false], c:3}
Note: If you don't consider the full object to be a "value", just remove the last item.

Categories

Resources