我发现很难将类似json的字符串变成json / dict对象,我已经得到了这样的数据
{"key1":"value1","key2":[{"key2.1":"value2.1"},{"key2.2":"value2.2"}]}
在变量上运行type
时,它告诉我它是str类<class 'str'>
。我需要将字符串转换为json或dict格式,以便我可以提取所有名为value的值...
我已经尝试了json.loads
,json.load
,json.dumps
,ast.literal_eval
,但似乎没有任何效果。我尝试在字符串的任一侧添加['
和']
,但仍然没有运气。有任何想法吗?感谢
编辑:
我使用nodeJS后端向烧录服务器发送请求,nodeJS axios请求就是这个
get_values: (key_one, key_two) =>
axios.post('http://localhost:5000/example', {
key_one: key_one,
key_two: key_two
}).then(res => res.data),
在烧瓶那边我做这个
@app.route('/example', methods=["POST","OPTIONS"])
def example():
convert_data = request.get_data()
string_data = convert_data.decode('utf8').replace("'", '"')
new_string = "'''" + string_data + "'''"
print(json.loads(new_string))
然后我收到错误
答案 0 :(得分:1)
我稍微修改了你的功能:
@app.route('/example', methods=["POST","OPTIONS"])
def example():
convert_data = request.get_data()
string_data = convert_data.decode('utf8')
print(json.loads(string_data))
似乎string_data
已经是一个完美格式化的json字符串,您可以将其传递到loads
。我删除'
替换为"
这似乎是不必要的,并且肯定添加'''
,这将使该字符串成为Python多行字符串文字语法,但肯定会打破json兼容性,这是你的错误告诉你的是什么:
json.decoder.JSONDecodeError:期望值:第1行第1列(字符0)
这应该更接近你想要的。否则,请在运行此内容时告诉我string_data
内部究竟是什么。
答案 1 :(得分:-1)
不确定我是否正确理解了这个问题。但是,假设你有一个字符串如下:
var a = { “key1”:“value1”, “key2”:[{ “key2.1”:“value2.1” },{ “key2.2”:“value2.2” }] }
然后你可以这样做:
try {
const dictionary = JSON.parse(a)
console.log(dictionary.key1) // This will print value1
Object.keys(dictionary).map((key) => {
console.log(dictionary[key]);
});
} catch(e){
// do something with error here
}