我正在尝试解析包含java中重复键的Json文件。我正在使用此答案Parsing a json which contains duplicate keys中建议的方法。 如果我对Json进行硬编码,但是如果我从文件中读取它,那么该方法可以正常工作,只读取最后一个重复的密钥。请帮助,因为我想从文件中读取Json。提前谢谢。 代码:
import requests
import bs4.BeautifulSoup as bs
url="https://www.tennisexpress.com/mens-adidas-tennis-shoes"
req = requests.get(url)
soup = bs(req.text,'lxml') # lxml because page is more xml than html
arts = soup.findAll("a",class_="product")
Json文件:
public class am {
public static void main(String args[]) throws Exception
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("sample.json"));
JSONObject a=JSONObject.fromObject(obj);
JSONObject jsonObject=JSONObject.fromObject("{\n" +
" \"Data\": {\n" +
" \"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"c\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"f\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"h\"\n" +
" }\n" +
" },\"A\": {\n" +
" \"B\": {\n" +
" \"C\": \"x\",\n" +
" \"D\": {}\n" +
" },\n" +
" \"E\": {\n" +
" \"F\": \"y\"\n" +
" },\n" +
" \"G\": {\n" +
" \"H\": \"z\"\n" +
" }\n" +
" },\n" +
"
"\n" +
" }\n" +
"}");
System.out.println("Json objects are:::"+a);
System.out.println("Json objects are:::"+jsonObject);
}
}
输出:
{
"Data": {
"A": {
"B": {
"C": "c",
"D": {}
},
"E": {
"F": "f"
},
"G": {
"H": "h"
}
},"A": {
"B": {
"C": "x",
"D": {}
},
"E": {
"F": "y"
},
"G": {
"H": "z"
}
},
}
}
答案 0 :(得分:4)
如果您没有使用外部JSON库的约束,那么可以使用net.sf.json.JSONObject
来解析您的JSON字符串,它将接受带有重复键的JSON。它将通过将重复值存储到数组中来保留重复值。
JSONObject jsonObject = JSONObject.fromObject( "{\"Data\": {\"A\": {\"B\": {\"C\": \"c\",\"D\": {}},\"E\": {\"F\": \"f\"},\"G\": {\"H\": \"h\"}},\"A\": {\"B\": {\"C\": \"x\",\"D\": {}},\"E\": {\"F\": \"y\"},\"G\": {\"H\": \"z\"}}}}" );
System.out.println( "net.sf.json.JSONObject: " + jsonObject );
答案 1 :(得分:0)
您需要对JSON对象进行字符串化
a.toString()