Reputation: 103
Need help to convert below JSON string into JSON object.Even string JSON is valid json (verified by https://jsonlint.com/).
JSON:
{
"condition": "AND",
"rules": [{
"id": "amount",
"operator": "greater_or_equal",
"value": "900"
},
{
"condition": "AND",
"rules": [{
"id": "vendorname",
"operator": "equal",
"value": "US BANK NATIONAL ASSOCIATION"
},
{
"id": "vendorname",
"operator": "equal",
"value": "HANSEN SOLUTIONS LLC"
}
]
}
]
}
Upvotes: 2
Views: 13458
Reputation: 22534
Your JSON string is multiline. Multiline string should be stored using template literals, otherwise use string concatenation to represent your string.
The below exmaple uses template literals. It is used to represent multi line string.
var str = `{
"condition": "AND",
"rules": [{
"id": "amount",
"operator": "greater_or_equal",
"value": "900"
},
{
"condition": "AND",
"rules": [{
"id": "vendorname",
"operator": "equal",
"value": "US BANK NATIONAL ASSOCIATION"
},
{
"id": "vendorname",
"operator": "equal",
"value": "HANSEN SOLUTIONS LLC"
}
]
}
]
}`;
console.log(JSON.parse(str));
This is a single line string.
var str = '{"condition":"AND","rules":[{"id":"amount","operator":"greater_or_equal","value":"900"},{"condition":"AND","rules":[{"id":"vendorname","operator":"equal","value":"US BANK NATIONAL ASSOCIATION"},{"id":"vendorname","operator":"equal","value":"HANSEN SOLUTIONS LLC"}]}]}';
console.log(JSON.parse(str));
Upvotes: 4
Reputation: 1474
Need help to convert below JSON string into JSON object.Even string JSON is valid json (verified by https://jsonlint.com/).
JSON.parse(jsonString); Is a pure JavaScript approach so long as you can require a reasonably modern browser.
See also https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Update:
Try JSON.parse(JSON.stringify(TheString))
Upvotes: 3
Reputation: 1072
Just using
try {
let obj = JSON.parse( string);
} catch( e) {
// conversion fails
console.error( e )
}
Upvotes: 0