简体   繁体   English

将字符串解析为Json-JSON.Parse

[英]Parse string to Json - JSON.Parse

String stored in the DB (Json format): 存储在数据库中的字符串(Json格式):

{"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: 解析为JSON:

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

using JSfiddle it shows: 使用JSfiddle它显示:

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 ==> obj.requiredParam返回未定义

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

==> Works ==>作品

Main purpose is to use the obj.requiredParam Any suggestions? 主要目的是使用obj.requiredParam有什么建议吗?

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 我认为你的HTML看起来像这样

<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 因此,首先将引号替换为String.replace ,然后可以通过简单地对其进行解析来从中获取json对象

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

Fiddle https://jsfiddle.net/uyf9egxq/ 小提琴https://jsfiddle.net/uyf9egxq/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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