5

I'm working with React, and I send this information:

const imageServicesClean = JSON.stringify(imageServices);
const query = `
    mutation {
        companyUpdate(
                idCompany:${idCompany},
                name:${nameClean},
                imageServices:${imageServicesClean})
            {
            idCompany
            name
            imageServices {
                idImageService
                name
                url
                key
            }
        }
    }`;

And the imageServicesClean is sent in this way, but return error:

[{
    "idImageService": 1,
    "name": "Service1",
    "url": "",
    "key": "asdasdas"
}, {
    "idImageService": 2,
    "name": "Service2",
    "url": "sdsads",
    "key": "sddsfsds_"
}]

Because my GraphQL server (Laravel) just allows the variable without quotes, in this way:

[{
    idImageService: 1,
    name: "Service1",
    url: "",
    key: "sdofunc4938urcnnwikk"
}, {
    idImageService: 2,
    name: "Service2",
    url: "sdsads",
    key: "sddsfsdssss8347yuirh"
}]

So the function JSON.stringify don't work for build format in GraphQL. How can I convert the object array to GraphQL format in Javascript?

2
  • how about using JSON.parse(imageServices) ?
    – Jems
    Commented Feb 5, 2018 at 1:49
  • JSON.parse takes a JSON string as argument, which is not the case
    – Eric Taix
    Commented Feb 5, 2018 at 15:33

2 Answers 2

13

Finally this was my solution:

const imageServicesClean = JSON.stringify(imageServices);
const graphQLImageServices = imageServicesClean.replace(/"([^(")"]+)":/g,"$1:");

But finally I'm working with this library, it does everything for me: https://github.com/atulmy/gql-query-builder

1
  • 2
    Hi can i ask what the (") does? I thought this will be sufficient /"([^"]+)":/g,"$1:", so i'm trying to understand what is the purpose of ("). Thanks!
    – Vic
    Commented Jul 22, 2018 at 10:21
0

There is a bug in Albert reply. If you have ": somewhere in your string like "field": "\"Hello\": World", then after regexp replace you will end up with something like this: field: "\\Hello\\: World".

I fixed this by adding [^\\"]+ to the regexp, so it looks like

imageServicesClean.replace(/"([^(")"]+[^\\"]+)":/g, "$1:");

I am not quite sure if this is a right fix and do not causes any bugs, but it works for me for now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.