提取data中的x,并将其相加。
data ={"note":"This",
"count":[
{ "id" : "001","x" : "2","name" : "Chuck"} ,
{ "id" : "009","x" : "7", "name" : "Brent"}
]}
用json提取
// 请把代码文本粘贴到下方(请勿用图片代替代码)
import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import ssl
import json
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
data ={"note":"This",
"count":[
{ "id" : "001","x" : "2","name" : "Chuck"} ,
{ "id" : "009","x" : "7", "name" : "Brent"}
]}
info = json.loads(data)
print('User count:', len(info))
for item in info:
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])
1.我期待的结果是
x 2
x 7
2.但执行结果提示TypeError: the JSON object must be str, bytes or bytearray, not dict
3.我试了下如果将data转化为以下样式就可以了,但不知如何转化。另外,如果用data=data['count'],转化出来的数据不带”'''“,导致还是会报错。
data ='''[
{ "id" : "001", "x" : "2", "name" : "Chuck"} ,
{ "id" : "009", "x" : "7", "name" : "Brent"}
]'''
import urllib.request, urllib.parse, urllib.error
import json
data ='''{"note":"This",
"count":[
{ "id" : "001","x" : "2","name" : "Chuck"} ,
{ "id" : "009","x" : "7", "name" : "Brent"}
]}'''
info = json.loads(data)
print('User count:', len(info))
for item in info["count"]:
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])
哈哈,我也为1c来的。
手动去书写json格式的数据很容易出问题,也不是正常作业过程:
建议:
先使用json.dumps 将原始数据转换成json格式的数据,然后在用json.loads加载使用。
这样可以保证格式是正确的,同时也会省去你在数据处理是很多的格式转换。
Lst<String> allMobileList = new ArrayList<>();
allMobileList = JSONArray.parseArray(data,String.class);
StringBuffer sb = new StringBuffer();
for(String allMobile : allMobileList)
{
JSONObject js=JSONObject.parseObject(allMobile);
js.getString("x"); //这里就取出x的数据,相加的话你自己定义变量接受吧。
sb.append(js.getString("x")+",");
}
根据你的:但执行结果提示 TypeError: the JSON object must be str, bytes or bytearray, not dict
可以知道就是你对JSON的定义错了,改成提示的应该就行。另外对于以json格式存在的数据,我们可以编写parser来提取
只想拿个1c积分下个东西 谢谢
def read_corpus()
import json
path = ./xxxx.json
with open (path,'r' ,encoding = 'utf8') as f:
all_data = json.loads(f.read()
data = all_data["data"]