简体   繁体   中英

Parse string to Json - JSON.Parse

String stored in the DB (Json format):

{"requiredParam":"value"}

(Razor)Getting a string from the model:

<a id="link-test" asp-controller="TestController" asp-action="TestAction">@model.param</a>

Parsing into JSON:

<script>
var obj = JSON.Parse(document.getElementById("link-test").innerHTML);
var requiredParam = obj.requiredParam;
</script>

using JSfiddle it shows:

JSON.Parse("{"required.Param":"value"}")

==> not working (the string that i am trying to parse have this format with the double quotes)

==> obj.requiredParam returns undefined

JSON.Parse('{"required.Param":"value"}')

==> Works

Main purpose is to use the obj.requiredParam Any suggestions?

Try this:

JSON.Parse('{"'+required.Param+'":"'+value+'"}')

Edit: I did not understand the question properly.. Apologies.

How ever you can escape the " using regex.

var str = document.getElementById("link-test").innerHTML;
str = str.replace(/"/g, '\\"');
var obj = JSON.Parse(str);
var requiredParam = obj.requiredParam;

解决方案是使用JObject.Parse和GetValue如下:

<a id="demo" asp-controller="Demo" asp-action="Demo">@Newtonsoft.Json.Linq.JObject.Parse(model.RequiredParam).GetValue("requiredParam")</a>

I assume your html looks like this

<div id="link-test">{"requiredParam":"value"}</div>

So first replace the quotes with String.replace and then you can get the json object from it by simply parsing it

var elem = document.getElementById("link-test").innerHTML;
var obj = JSON.parse(elem.replace(/"/g, '\"'));
console.log(obj.requiredParam);

Fiddle https://jsfiddle.net/uyf9egxq/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM