简体   繁体   English

如何从Javascript中的json提取值?

[英]How to extract value from json in Javascript?

I am trying to read first value from below json array 我正在尝试从json数组下面读取第一个值

 var json = "[{\"First\",\"Second\"}]";

How do i get value first from above json array. 我如何首先从上面的json数组获取价值。

    var result = JObject.Parse(json);
   var result = JArray.Parse(json);

I tried above things but both throwing exception. 我在上面尝试过,但是都抛出异常。

Newtonsoft.JSON is a good solution for this kind of situations. Newtonsoft.JSON是针对这种情况的良好解决方案。 Also Newtonsof.JSON is faster than others such as JavaScriptSerializer , DataContractJsonSerializer . 而且Newtonsof.JSON比其他JavaScriptSerializerDataContractJsonSerializer更快。

In this sample , you can the following : 在此示例中,您可以执行以下操作:

var jsonData = JObject.Parse("your json data here");

Then you can cast jsonData to JArray and you can use for loop to get data at each iteration. 然后,您可以将jsonData强制转换为JArray,并且可以使用for循环在每次迭代时获取数据。 Also, I want to add something. 另外,我想添加一些东西。

Working with dynamic object and using Newtonsoft serialize is a good choice. 使用动态对象并使用Newtonsoft序列化是一个不错的选择。

var json = "[{\"First\",\"Second\"}]";

dynamic result = JsonConvert.DeserializeObject(json);

As you are using jObject It's look like c# code. 在使用jObject时,它看起来像c#代码。 You can read the json as the given code. 您可以阅读json作为给定的代码。

JSON is not a list format, but works like a key value data structure. JSON不是列表格式,但是像键值数据结构一样工作。 Try this little Javascript in your browser console to understand, how it is supposed to work. 浏览器控制台中尝试使用这个小Javascript,以了解它应该如何工作。

obj = JSON.parse("{\"first\":\"First value\", \"second\":\"Second Value, maybe some more text?\"}");
console.log(obj.first);
console.log(obj.second);

Prints: 印刷品:

First value
Second Value, maybe some more text?

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

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