Project

General

Profile

Actions

Bug #16825

closed

JSON#generate gives invalid json string

Added by definitely_not_a_bot (Definitely Not A Bot) over 5 years ago. Updated about 5 years ago.

Status:
Third Party's Issue
Assignee:
-
Target version:
-
[ruby-core:98113]

Description

Hello Guys! First of all, thank you for working on the Ruby language.

I observed a peculiarity while playing around with JSON#generate. When hash contains keys of the same word/literal but as symbol and string in the same hash, the JSON#generate creates JSON string with a duplicate key.

require 'json'

my_hash = { key: "symbol", "key" => "string" }

JSON.generate(my_hash) #=> "{\"key\":\"symbol\",\"key\":\"string\"}"

Expected:

JSON.generate(my_hash) #=> "{\"key\":\"string\"}"

I am new to ruby, so not sure if this right platform to report this observation. I do feel like the current result is the desired result but found it little odd behavior.

Please do close this issue if, it is not the right platform for the issue or it is the intended behavior.

Updated by nobu (Nobuyoshi Nakada) over 5 years ago

  • Status changed from Open to Third Party's Issue

Interesting.

As JSON.generate converts the keys by to_s, it can be funnier.

$ ruby -rjson -e 'puts JSON.generate({"main"=>"string", :main=>"symbol", self=>"object"})'
{"main":"string","main":"symbol","main":"object"}

Anyway, https://github.com/flori/json is the upstream of the bundled json library.

Updated by shyouhei (Shyouhei Urabe) over 5 years ago

Actually it is not an invalid JSON in any sense. RFC 8259 section 4 explicitly allows such duplicated names:
https://tools.ietf.org/html/rfc8259#section-4

Updated by definitely_not_a_bot (Definitely Not A Bot) about 5 years ago

shyouhei (Shyouhei Urabe) wrote in #note-2:

Actually it is not an invalid JSON in any sense. RFC 8259 section 4 explicitly allows such duplicated names:
https://tools.ietf.org/html/rfc8259#section-4

I am little confused now, RFC states that

The names within an object SHOULD be unique.

But it also states that

When the names within an object are not
unique, the behavior of software that receives such an object is
unpredictable. Many implementations report the last name/value pair
only. Other implementations report an error or fail to parse

So what should be correct behaviour.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0