我正在尝试在此代码中选择特定的密钥,即163,203& 13.基本上,每次,我的函数运行,我将在变量中存储这3个代码中的一个,我无法弄清楚如何解析Json文件中的特定元素。我想制作一个循环,例如在键'203'停止并返回结果。
function* ChatRoomPageEnter() {
const chanChat = yield call($stomp.eventChannel, 'ChatRoomPage', '/topic/chat');
const chanEcho = yield call($stomp.eventChannel, 'ChatRoomPage', '/user/queue/echo');
while (true) { // eslint-disable-line no-constant-condition
console.log('A');
const messageChat = yield take(chanChat);
console.log('B');
yield put({ type: 'chatroom/newMessage', payload: messageChat });
console.log('C'); // <----
const messageEcho = yield take(chanEcho);
console.log('D');
yield put({ type: 'chatroom/newMessage', payload: messageEcho });
console.log('E');
}
}
这是JSON。 JSON分为3个部分,每个部分以随机密钥开头,我不知道,如果你看JSON,在有效载荷之后,有价格,然后是id(例如'203')。我需要获得此id的值。
with open('data.json') as data_file:
data = json.load(data_file, object_pairs_hook=OrderedDict)
for key, value in data.items():
id = '203'
id_value = value['payload']['price']
pack = id_value[id]
print(pack) #pack should be returning the value of the key '203'
答案 0 :(得分:1)
在访问它之前检查它存在的ID是错误的。
import json
from collections import OrderedDict
id = '203'
with open('data,json') as data_file:
data = json.load(data_file, object_pairs_hook=OrderedDict)
for key, value in data.items():
id_value = value['payload']['price']
if id in id_value: # check first if id is present
pack = id_value[id]
print(pack) #pack should be returning the value of the key '203'
答案 1 :(得分:0)
with open('data.json') as data_file:
data = json.load(data_file, object_pairs_hook=OrderedDict)
for key, value in data.items():
id = '203'
if value['payload']['price'] == id:
print(value['payload']['price'])
这是我可以从你的问题中得出的结果。如果那不符合预期,请在下面评论。
答案 2 :(得分:0)
我尝试展平JSON对象,以便所有键都处于同一级别。
import json
from pandas.io.json import json_normalize
from collections import OrderedDict
with open('data.json') as data_file:
data = json.load(data_file, object_pairs_hook=OrderedDict)
data=json_normalize(data)
id='163'
for key, value in data.items():
nested_ids = key.split('.')
if (id in nested_ids):
print(value)
这会让你朝着正确的方向前进吗?