C ++:解析JSON字符串,键不包括在双引号中 [英] C++: parsing JSON string, having keys not enclosed into double quotes

查看:859
本文介绍了C ++:解析JSON字符串,键不包括在双引号中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功使用Casablanca Json C ++库(cpprest)一段时间了。其解析器( web :: json :: value :: parse(< json_string>))在有效 JSON字符串上正常工作。假设这将正确解析:

  {
key1:[[1,0.4] 0,0.6]],
key2:true,
key3:1,
key4:[{key41:1} [1,2,3]}]
}

解析JSON对象,其键不包含在双引号中:

  {
key1:[[ 0.4],[0,0.6]],
key2:true,
key3:1,
key4:[{key41:1},{key42:[1,2,3] ]
}

有一个很好的方法来正确解析这个,然后序列化成有效JSON,以便Casablanca可以正确解析生成的有效JSON?



Hjson 似乎工作的目的,但它不提供所需的C ++库。他们提到 jzon library for C - 我试过:它只有单向解析(没有序列化),甚至解析不能正确工作(甚至不能解析有效的JSON)

解决方案

这可能不是最快的方法,代码,它会来得很高。



你有一个类似javascript的对象。让我们把它插入一个javascript引擎,并使用它吐出正确的JSON。我会使用Qt的 QJSngine ,因为我熟悉它:

  constexpr char const * str = R({
key1:[[1,0]],[0,0.6]],
key2:true,
key3:1,
key4:[{key41:1},{key42:[1,2,3]}]
});

QJSEngine e;

QString script = QString(JSON.stringify(%0))。arg(str);

那么你可以评估它:

  e.evaluate(script).toString()。toStdString()

产生

  {key1:[[1,0.4],[0,0.6]],key2 :true,key3:1,key4:[{key41:1},{key42:[1,2,3]}]} 
pre>

I've been using Casablanca Json C++ library (cpprest) successfully for some time. Its parser (web::json::value::parse(<json_string>)) works perfectly on valid JSON strings. Say this will be parsed correctly:

{
  "key1": [["1", 0.4], ["0", 0.6]],
  "key2": true,
  "key3": 1,
  "key4": [{"key41": 1}, {"key42": [1,2,3]}]
}    

Now, I faced the necessity of parsing JSON objects, the keys of which are not enclosed into double quotes:

{
  key1: [[1, 0.4], [0, 0.6]],
  key2: true,
  key3: 1,
  key4: [{key41: 1}, {key42: [1,2,3]}]
}

Is there a nice way to correctly parse this and then serialize into a valid JSON, so that Casablanca can parse the resultant valid JSON correctly?

Hjson seems to work for this purpose, but it doesn't provide the required library for C++. They mention jzon library for C - I tried it: it has only one-way parsing (no serialization), and even parsing doesn't work correctly (can't even parse valid JSONs)

解决方案

This probably won't be the fastest way to do this, but if niceness is measured in least lines of code, it'll come up pretty high.

What you have is a javascript-like object. Let's plug it into a javascript engine and use it to spit out proper JSON. I'll use Qt's QJSEngine since I'm passably familiar with it:

constexpr char const* str = R"({
    key1: [[1, 0.4], [0, 0.6]],
    key2: true,
    key3: 1,
    key4: [{key41: 1}, {key42: [1,2,3]}]
})";

QJSEngine e;

QString script = QString("JSON.stringify(%0)").arg(str);

then you can just evaluate it:

e.evaluate(script).toString().toStdString()

yields

{"key1":[[1,0.4],[0,0.6]],"key2":true,"key3":1,"key4":[{"key41":1},{"key42":[1,2,3]}]}

这篇关于C ++:解析JSON字符串,键不包括在双引号中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆