Om Chaturvedi
Om Chaturvedi

Reputation: 103

JSON.parse is not working for converting JSON string to JSON object

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

Answers (3)

Hassan Imam
Hassan Imam

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

Divide by Zero
Divide by Zero

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

sfrehse
sfrehse

Reputation: 1072

Just using

try {
      let obj = JSON.parse( string);
} catch( e) {
    // conversion fails
   console.error( e ) 
} 

Upvotes: 0

Related Questions