New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Serializing nested arrays to Json results in a flat array #840

Closed
ReneZwanenburg opened this Issue Sep 23, 2014 · 0 comments

Comments

Projects
None yet
1 participant
@ReneZwanenburg
Contributor

ReneZwanenburg commented Sep 23, 2014

import vibe.d;
import std.stdio;

void main()
{
    float[4][4] matrix;
    matrix.serializeToJson.toString.writeln;
}

[nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan,nan]

The issue is caused by the ~= implementation for Json arrays.
From Json.opOpAssign:

if (other.m_type == Type.array) m_array ~= other.m_array;

From JsonSerializer:

void endWriteArray(T)() { m_current = m_compositeStack[$-1]; m_compositeStack.length--; }
void endWriteArrayEntry(T)(size_t) { m_compositeStack[$-1] ~= m_current; }

When the serializer finishes serializing the nested array, endWriteArray is called. Then m_current is the nested array, and the outer array sits at the top of m_compositeStack.

Next, endWriteArrayEntry is called because the nested array is of course an entry of the outer array. As you can see in opOpAssign this will append the arrays together instead of appending the inner array as an element of the outer array.

While it makes sense for ~= to have D's 'append arrays' behavior by default, Json needs a way to append an array to another array as element. Then JsonSerializer.endWriteArrayEntry can use this method instead.

I'm of course willing to write the patch, but I'd like your opinion on the solution first. Is it acceptable to add such a method to Json? I was thinking of Json.appendArrayElement(Json), the long name shouldn't be a problem as it's not needed very often. The comments should explain it's only use case is creating nested arrays.

@s-ludwig s-ludwig closed this in b20c40b Sep 26, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment