$.each(data,function(){
$.each(this.subcatagory,function(){
$("#_select").append("<option>"+this.name+"</option>");
});
});
B. json是什么文件
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming Language,Standard ECMA-262 3rd Edition - December 1999的一个子集。
JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。 这些特性使JSON成为理想的数据交换语言。
JSON建构于两种结构,一是“名称/值”对的集合(Acollectionofname/valuepairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hashtable),有键列表(keyedlist),或者关联数组(associativearray)。
二是值的有序列表(Anorderedlistofvalues)。在大部分语言中,它被理解为数组(array)。
(2)看json文件有多少层扩展阅读:
JSON简要历史
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。
JSON是Douglas Crockford在2001年开始推广使用的数据格式,在2005年-2006年正式成为主流的数据格式,雅虎和谷歌就在那时候开始广泛地使用JSON格式。
C. 怎么用程序解析一个json文件
一、要解决这个问题首先要知道json格式是什么?
JSON格式:
比如学生有学号,姓名,性别等。
用表示则为:
{"studno":"11111","studname":"wwww","studsex":"男"}(各个字段都是字符型)
这代表一个学生的信息。
如果多个呢?
[{"studno":"122222","studname":"wwww","studsex":"男"},
{"studno":"11111","studname":"xxxx","studsex":"男"},
{"studno":"33333","studname":"ssss","studsex":"男"}]
这就是json格式。
二、那如何操作json格式的文件呢?
这个更简单了,说白了就是直接读写文件,再把读出来的文件内容格式化成json就可以了。
三、具体操作。
1.我有一个实体类,如下:
public class ElectSet {
public String xueqi;
public String xuenian;
public String startTime;
public String endTime;
public int menshu;
public String isReadDB;
//{"xueqi":,"xuenian":,"startTime":,"endTime":,"renshu":,"isReadDB":}
public String getXueqi() {
return xueqi;
}
public void setXueqi(String xueqi) {
this.xueqi = xueqi;
}
public String getXuenian() {
return xuenian;
}
public void setXuenian(String xuenian) {
this.xuenian = xuenian;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public int getMenshu() {
return menshu;
}
public void setMenshu(int menshu) {
this.menshu = menshu;
}
public String getIsReadDB() {
return isReadDB;
}
public void setIsReadDB(String isReadDB) {
this.isReadDB = isReadDB;
}
}
2.有一个json格式的文件,存的就是他的信息,如下
Sets.json:
{"xuenian":"2007-2008","xueqi":"1","startTime":"2009-07-19 08:30","endTime":"2009-07-22 18:00","menshu":"10","isReadDB":"Y"}
3.具体操作.
/*
* 取出文件内容,填充对象
*/
public ElectSet findElectSet(String path){
ElectSet electset=new ElectSet();
String sets=ReadFile(path);//获得json文件的内容
JSONObject jo=JSONObject.fromObject(sets);//格式化成json对象
//System.out.println("------------" jo);
//String name = jo.getString("xuenian");
//System.out.println(name);
electset.setXueqi(jo.getString("xueqi"));
electset.setXuenian(jo.getString("xuenian"));
electset.setStartTime(jo.getString("startTime"));
electset.setEndTime(jo.getString("endTime"));
electset.setMenshu(jo.getInt("menshu"));
electset.setIsReadDB(jo.getString("isReadDB"));
return electset;
}
//设置属性,并保存
public boolean setElect(String path,String sets){
try {
writeFile(path,sets);
return true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
//读文件,返回字符串
public String ReadFile(String path){
File file = new File(path);
BufferedReader reader = null;
String laststr = "";
try {
//System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
//一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
//显示行号
System.out.println("line " line ": " tempString);
laststr = laststr tempString;
line ;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return laststr;
}
//把json格式的字符串写到文件
public void writeFile(String filePath, String sets) throws IOException {
FileWriter fw = new FileWriter(filePath);
PrintWriter out = new PrintWriter(fw);
out.write(sets);
out.println();
fw.close();
out.close();
}
4.调用,使用(在网站的controller里调用的)
//取出json对象
public void GetElectSettings(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ElectSet electset=new ElectSet();
String absPath = request.getRealPath("\");
String filePath = absPath "public\sets\electSets.json";
electset=businessService.findElectSets(filePath);//这里是调用,大家自己改改,我调用的业务层 的。
JSONArray jsonItems = new JSONArray();
jsonItems.add(electset);
JSONObject jo=new JSONObject();
jo.put("data", jsonItems);
System.out.println(jo);
request.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(jo);
}
//修改json文件
public void ChangeElectSet(HttpServletRequest request,
HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/json;charset=utf-8");
log.info("reach ChangeElectSet");
String json = (String) request.getParameter("json").trim();
log.info("Change ElectSet");
log.info(json);
ElectSet sets = new ElectSet();
JSONObject jsonObject = JSONObject.fromObject(json);
sets = (ElectSet) JSONObject.toBean(jsonObject, ElectSet.class);
if(sets.getIsReadDB()=="false"){
sets.setIsReadDB("否");
}
else{
sets.setIsReadDB("是");
}
String changes="{"xuenian":"";//因为json的属性要用引号,所以要用"转义一下
changes =sets.getXuenian() "","xueqi":"" sets.getXueqi() "","startTime":"" sets.getStartTime() "","endTime":"" sets.getEndTime() "","menshu":"" sets.getMenshu() "","isReadDB":"" sets.getIsReadDB() ""}";
System.out.println(changes);
String absPath = request.getRealPath("\");
String filePath = absPath "public\sets\electSets.json";
转载
D. json配置文件,如何在打开json文件时,缩进和分组,显示标签的分组层次结构(注意,各分组可折叠或伸展)
用记事本就可以打开了。换句话说,任何文本编辑工具都可以打开。
json只是一种约定的格式,一般是给程序读取的。
最常见的是浏览器收藏格式,也可以使用浏览器打开。
E. 怎么在浏览器上查看json数据
浏览器上查看json数据的办法。如下参考:
1.先打开编写的软件web程序。
F. 怎么生成和解析iOS开发JSON格式数据
导语:JSON作为数据包格式传输的时候具有更高的效率,这是因为JSON不像XML那样需要有严格的闭合标签,这就让有效数据量与总数据包比大大提升,从而减少同等数据流量的情况下,网络的传输压力。JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是JavaScript很容易解释它,而且 JSON 可以表示比"名称 / 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表。
一、如何生成JSON格式的'数据?
1、利用字典NSDictionary转换为键/值格式的数据。
// 如果数组或者字典中存储了 NSString, NSNumber, NSArray, NSDictionary, or NSNull 之外的其他对象,就不能直接保存成文件了.也不能序列化成 JSON 数据.
NSDictionary *dict = @{@"name" : @"me", @"do" : @"something", @"with" : @"her", @"address" : @"home"};
// 1.判断当前对象是否能够转换成JSON数据.
// YES if obj can be converted to JSON data, otherwise NO
BOOL isYes = [NSJSONSerialization isValidJSONObject:dict];
if (isYes) {
NSLog(@"可以转换");
/* JSON data for obj, or nil if an internal error occurs. The resulting data is a encoded in UTF-8.
*/
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
/*
Writes the bytes in the receiver to the file specified by a given path.
YES if the operation succeeds, otherwise NO
*/
// 将JSON数据写成文件
// 文件添加后缀名: 告诉别人当前文件的类型.
// 注意: AFN是通过文件类型来确定数据类型的!如果不添加类型,有可能识别不了! 自己最好添加文件类型.
[jsonData writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/dict.json" atomically:YES];
NSLog(@"%@", [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
} else {
NSLog(@"JSON数据生成失败,请检查数据格式");
}
2、通过JSON序列化可以转换数组,但转换结果不是标准化的JSON格式。
NSArray *array = @[@"qn", @18, @"ya", @"wj"];
BOOL isYes = [NSJSONSerialization isValidJSONObject:array];
if (isYes) {
NSLog(@"可以转换");
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:NULL];
[data writeToFile:@"/Users/SunnyBoy/Sites/JSON_XML/base" atomically:YES];
} else {
NSLog(@"JSON数据生成失败,请检查数据格式");
}
二、如何解析JSON格式的数据?
1、使用TouchJSon解析方法:(需导入包:#import "TouchJson/JSON/CJSONDeserializer.h")
//使用TouchJson来解析北京的天气
//获取API接口
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];
//定义一个NSError对象,用于捕获错误信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"jsonString--->%@",jsonString);
//将解析得到的内容存放字典中,编码格式为UTF8,防止取值的时候发生乱码
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
//因为返回的Json文件有两层,去第二层内容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);
//取值打印
NSLog(@"%@",[NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
2、使用SBJson解析方法:(需导入包:#import "SBJson/SBJson.h")
//使用SBJson解析北京的天气
NSURL *url = [NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"%@", [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]]);
3、使用IOS5自带解析类NSJSONSerialization方法解析:(无需导入包,IOS5支持,低版本IOS不支持)
// 从中国天气预报网请求数据
NSURL *url = [ NSURL URLWithString:@"http://www.weather.com.cn/adat/sk/101010100.html"];
// 创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 在网络完成的 Block 回调中,要增加错误机制.
// 失败机制处理: 错误的状态码!
// 最简单的错误处理机制:
if (data && !error) {
// JSON格式转换成字典,IOS5中自带解析类NSJSONSerialization从response中解析出数据放到字典中
id obj = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSDictionary *dict = obj[@"weatherinfo"];
NSLog(@"%@---%@", dict, dict[@"city"]);
}
}] resume];
4、使用JSONKit的解析方法:(需导入包:#import "JSONKit/JSONKit.h")
//如果json是“单层”的,即value都是字符串、数字,可以使用objectFromJSONString
NSString *json1 = @"{"a":123, "b":"abc"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
//如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能会报错(测试结果表明:使用由网络或得到的php/json_encode生成的json时会报错,但使用NSString定义的json字符串时,解析成功),最好使用:
NSString *json2 = @"{"a":123, "b":"abc", "c":[456, "hello"], "d":{"name":"张三", "age":"32"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 :JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
G. iOS开发问题:已经获得了json字符串,怎么解析并显示到tableview上
作为一种轻量级的数据交换格式,json正在逐步取代xml,成为网络数据的通用格式。
有的json代码格式比较混乱,可以使用此“http://www.bejson.com/”网站来进行JSON格式化校验(点击打开链接)。此网站不仅可以检测Json代码中的错误,而且可以以视图形式显示json中的数据内容,很是方便。
从IOS5开始,APPLE提供了对json的原生支持(NSJSONSerialization),但是为了兼容以前的ios版本,可以使用第三方库来解析Json。
本文将介绍TouchJson、 SBJson 、JSONKit 和 iOS5所支持的原生的json方法,解析国家气象局API,TouchJson和SBJson需要下载他们的库
TouchJson包下载: http://download.csdn.net/detail/enuola/4523169
SBJson 包下载: http://download.csdn.net/detail/enuola/4523177
JSONKit包下载:http://download.csdn.net/detail/enuola/4523160
下面的完整程序源码包下载:http://download.csdn.net/detail/enuola/4523223
PS:
国家气象局提供的天气预报接口
接口地址有三个:
http://www.weather.com.cn/data/sk/101010100.html
http://www.weather.com.cn/data/cityinfo/101010100.html
http://m.weather.com.cn/data/101010100.html
第三接口信息较为详细,提供的是6天的天气,关于API所返回的信息请见开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供),全国各城市对应这一个id号,根据改变id好我们就可以解析出来各个城市对应天气;
下面介绍四种方法解析JSON:
首先建立一个新的工程,(注意不要选择ARC机制)添加如下控件:
如上图所示。下面展出程序代码:
文件 ViewController.h 中:
[cpp] view plain
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (retain, nonatomic) IBOutlet UITextView *txtView;
- (IBAction)btnPressTouchJson:(id)sender;
- (IBAction)btnPressSBJson:(id)sender;
- (IBAction)btnPressIOS5Json:(id)sender;
- (IBAction)btnPressJsonKit:(id)sender;
@end
文件ViewController.m中主要代码:
(1)使用TouchJSon解析方法:(需导入包:#import "TouchJson/JSON/CJSONDeserializer.h")
[cpp] view plain
//使用TouchJson来解析北京的天气
- (IBAction)btnPressTouchJson:(id)sender {
//获取API接口
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];
//定义一个NSError对象,用于捕获错误信息
NSError *error;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(@"jsonString--->%@",jsonString);
//将解析得到的内容存放字典中,编码格式为UTF8,防止取值的时候发生乱码
NSDictionary *rootDic = [[CJSONDeserializer deserializer] deserialize:[jsonString dataUsingEncoding:NSUTF8StringEncoding] error:&error];
//因为返回的Json文件有两层,去第二层内容放到字典中去
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
NSLog(@"weatherInfo--->%@",weatherInfo);
//取值打印
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
}
(2)使用SBJson解析方法:(需导入包:#import "SBJson/SBJson.h")
[cpp] view plain
//使用SBJson解析南阳的天气
- (IBAction)btnPressSBJson:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101180701.html"];
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *rootDic = [parser objectWithString:jsonString error:&error];
NSDictionary *weatherInfo = [rootDic objectForKey:@"weatherinfo"];
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
}
(3)使用IOS5自带解析类NSJSONSerialization方法解析:(无需导入包,IOS5支持,低版本IOS不支持)
[cpp] view plain
- (IBAction)btnPressIOS5Json:(id)sender {
NSError *error;
//加载一个NSURL对象
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];
//将请求的url数据放到NSData对象中
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//IOS5自带解析类NSJSONSerialization从response中解析出数据放到字典中
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];
txtView.text = [NSString stringWithFormat:@"今天是 %@ %@ %@ 的天气状况是:%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];
NSLog(@"weatherInfo字典里面的内容为--》%@", weatherDic );
}
(4)使用JSONKit的解析方法:(需导入包:#import "JSONKit/JSONKit.h")
[cpp] view plain
- (IBAction)btnPressJsonKit:(id)sender {
//如果json是“单层”的,即value都是字符串、数字,可以使用objectFromJSONString
NSString *json1 = @"{\"a\":123, \"b\":\"abc\"}";
NSLog(@"json1:%@",json1);
NSDictionary *data1 = [json1 objectFromJSONString];
NSLog(@"json1.a:%@",[data1 objectForKey:@"a"]);
NSLog(@"json1.b:%@",[data1 objectForKey:@"b"]);
[json1 release];
//如果json有嵌套,即value里有array、object,如果再使用objectFromJSONString,程序可能会报错(测试结果表明:使用由网络或得到的php/json_encode生成的json时会报错,但使用NSString定义的json字符串时,解析成功),最好使用:
NSString *json2 = @"{\"a\":123, \"b\":\"abc\", \"c\":[456, \"hello\"], \"d\":{\"name\":\"张三\", \"age\":\"32\"}}";
NSLog(@"json2:%@", json2);
NSDictionary *data2 = [json2 :JKParseOptionLooseUnicode];
NSLog(@"json2.c:%@", [data2 objectForKey:@"c"]);
NSLog(@"json2.d:%@", [data2 objectForKey:@"d"]);
[json2 release];
}
另外,由于iOS5新增了JSON解析的API,我们将其和其他五个开源的JSON解析库进行了解析速度的测试,下面是测试的结果。
我们选择的测试对象包含下面的这几个框架,其中NSJSONSerialization是iOS5系统新增的JSON解析的API,需要iOS5的环境,如果您在更低的版本进行测试,应该屏蔽相应的代码调用。
- [SBJSON (json-framework)](http://code.google.com/p/json-framework/)
- [TouchJSON (from touchcode)](http://code.google.com/p/touchcode/)
- [YAJL (objective-C bindings)](http://github.com/gabriel/yajl-objc)
- [JSONKit](https://github.com/johnezang/JSONKit)
- [NextiveJson](https://github.com/nextive/NextiveJson)
-[NSJSONSerialization](http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010946)
我们选择了四个包含json格式的数据的文件进行测试。每一个文件进行100的解析动作,对解析的时间进行比较。
.....
测试的结果显示,系统的API的解析速度最快,我们在工程项目中选择使用,也是应用较为广泛的SBJSON的解析速度为倒数第二差,令我大跌眼镜。
与系统API较为接近的应该是JSONKit。
这里没有对API的开放接口和使用方式进行比较,若单纯基于以上解析速度的测试:
1:iOS5应该选择系统的API进行
2:不能使用系统API的应该选择JSONKit
解决方案来源于网络,但是我看了,没有问题。还是建议采用第三种苹果自带方法解决这个问题。
参考:http://blog.csdn.net/enuola/article/details/7903632/
H. 如何用Python解析多层嵌套的JSON
单纯从你给的这个链接,使用requests.get(url).json()
这样拿到的数据,是dict类型,取值正常.....