发送/解析多个JSON对象 [英] Sending/Parsing multiple JSON objects

查看:161
本文介绍了发送/解析多个JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Sinatra服务器,它以流方式从数据库返回多个JSON对象。对象看起来像:

I have a Sinatra server that is returning multiple JSON objects from the database in a streaming manner. The objects would look like:

{"a": 1, "b": 2, "c": 3}
{"a": 4, "b": 5, "c": 6}
...

但这是无效的JSON。我可以在Sinatra的事件处理中添加一个hack(手动注入缺少的数组分隔符),使响应看起来像:

but this is invalid JSON. I can add a hack into Sinatra's event processing (manually injecting the missing array delimiters) to make the response look like:

[
{"a": 1, "b": 2, "c": 3}
, {"a": 4, "b": 5, "c": 6}
]

现在是有效的JSON,但这种技术不够优雅。有没有办法做这个客户端?基本上,我想要的是让一个JavaScript函数读取一个字符串并使用一个有效的JSON对象,然后返回给我JSON对象和字符串的其余部分,迭代地调用直到整个字符串被消耗。

which is valid JSON now, but this technique is inelegant. Is there some way to do this client-side? Basically, what I want is to have a JavaScript function read a string and consume a valid JSON object, and then return to me the JSON object and the remainder of the string, iteratively being called until the entire string is consumed.

推荐答案

本机 JSON.parse()函数期望整个字符串有效JSON 。我不知道一个解析器只消耗你想要的第一个有效对象。无论如何,人们应该真正生成有效的JSON。

The native JSON.parse() function expect the whole string to be valid JSON. I'm not aware of a parser that only consumes the first valid object as you'd like. And people should really be producing valid JSON anyways.

如果您知道每行有一个对象,您可以使用 split()函数并分别解析每一行。

If you know that there is one object per line you could simply split the string by line using the split() function and parse each line individually.

var str = '{"a": 1, "b": 2, "c": 3}\n'+
          '{"a": 4, "b": 5, "c": 6}';

var strLines = str.split("\n");


for (var i in strLines) {
  var obj = JSON.parse(strLines[i]);
  console.log(obj.a);
}

您还可以使用一些字符串操作将每行转换为数组元素和解析整个事情。

You could also use a bit of string manipulation to transform each line into an array element and parse the whole thing.

str = "["+str.replace(/\n/g, ",")+"]";
JSON.parse(str);

这篇关于发送/解析多个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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