$.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類型,取值正常.....