how convert string to object in javaScript
Although you haven't mentioned JSON explicitly, this data looks like JSON. You can use JSON.parse() to turn JSON strings into JavaScript variables
However, the string you've posted isn't actually valid JSON because of a couple of syntax errors. You can fix those to get (what I assume is) the intended object structure:
1) remove the extra double-quote before new jersey
2) add curly braces at either end to make it into a valid object.
3) remove extra comma after the last array entry (although a lot of parsers will tolerate this in fact)
So you end up with
{
"users": [
{ "name":"John", "age":30, "city":"New York"},
{ "name":"Mike", "age":25, "city":"new jersey"}
]
}
And this can be parsed easily:
var obj = '{ "users": [{ "name": "John", "age": 30, "city": "New York" }, { "name": "Mike", "age": 25, "city": "new jersey" }]}';
var data = JSON.parse(obj);
console.log(data);console.log("----------");
//example of gettng a specific property, now it's a JS variableconsole.log(data.users[0].name);
Converting string to object with Javascript
"JwtBody { user_id: 1, auth_id: 1}" is obviously not a standard json string,So you can try this.
function strToObj(str){
var obj = {};
if(str&&typeof str ==='string'){
var objStr = str.match(/\{(.)+\}/g);
eval("obj ="+objStr);
}
return obj
}
Safely turning a JSON string into an object
JSON.parse(jsonString)
is a pure JavaScript approach so long as you can guarantee a reasonably modern browser.
javascript string to object
var str='{"a":"www"}';
var obj = JSON.parse(str);
convert string to object from html input element
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>
JavaScript Split String into Object with Properties
If order.customer.note
is your example string, then this should work:
let data = "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n";//let data = JSON.stringify(rawNoteData); <-- Don't do this. order.customer.note is not an object.
let foo = data.split("\n").reduce(function(obj, str, index) { let strParts = str.split(":"); if (strParts[0] && strParts[1]) { //<-- Make sure the key & value are not undefined obj[strParts[0].replace(/\s+/g, '')] = strParts[1].trim(); //<-- Get rid of extra spaces at beginning of value strings } return obj;}, {});
console.log(foo);
Convert String to Object gives error due to double quotes at start and end
try this
const jsonStr =
'"{ "type": "object", "properties": { "hostUrl": { "type": "string", "description": "hostUrl", }, }, }"';
var json = jsonStr
.substring(1, jsonStr.length - 1)
.replaceAll("},", "}")
.replaceAll(" ", "")
.replaceAll(",}", "}");
json
{
"type": "object",
"properties": {
"hostUrl": {
"type": "string",
"description": "hostUrl"
}
}
}
Related Topics
Differencebetween JavaScript Promises and Async Await
Using Jquery to Replace One Tag with Another
Make Browser Window Blink in Task Bar
How to Extend Function with Es6 Classes
How to Prevent Form from Submitting Multiple Times from Client Side
Adding Console.Log to Every Function Automatically
How Do Browsers Pause/Change JavaScript When Tab or Window Is Not Active
Idiomatically Find the Number of Occurrences a Given Value Has in an Array
How to Add a Tooltip to an Svg Graphic
Getting the Return Value of JavaScript Code in Selenium
What Does [Object Object] Mean? (Javascript)
Most Efficient Way to Concatenate Strings in JavaScript
How to Trigger the Window Resize Event in JavaScript
I Want to Remove Double Quotes from a String
JavaScript Sleep/Wait Before Continuing
Is JavaScript an Untyped Language
Uncaught Typeerror: Illegal Invocation in JavaScript
Regarding Promises/A+ Specification, Differencebetween the Terms "Thenable" and "Promise"