Make JSON-C (libjson)

So you want to parse JSON with C? Welcome aboard! First get json-c, configure, compile, and update your ld cache

Make JSON-C (libjson)

x86 / Ubuntu

wget http://oss.metaparadigm.com/json-c/json-c-0.9.tar.gz
tar xf json-c-0.9.tar.gz
cd json-c-0.9
./configure && make && sudo make install
sudo ldconfig

ARM / OpenEmbedded

bitbake json-c

Simple Test

Now use one of the test files provided or this example: http://www.jroller.com/RickHigh/entry/json_parsing_with_c_simple

json-example.c:

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#include <json/json.h>

int main(int argc, char **argv)
{
  struct json_object *new_obj;
  new_obj = json_tokener_parse("/* more difficult test case */ { \"glossary\": { \"title\": \"example glossary\", \"pageCount\": 100, \"GlossDiv\": { \"title\": \"S\", \"GlossList\": [ { \"ID\": \"SGML\", \"SortAs\": \"SGML\", \"GlossTerm\": \"Standard Generalized Markup Language\", \"Acronym\": \"SGML\", \"Abbrev\": \"ISO 8879:1986\", \"GlossDef\": \"A meta-markup language, used to create markup languages such as DocBook.\", \"GlossSeeAlso\": [\"GML\", \"XML\", \"markup\"] } ] } } }");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  new_obj = json_object_object_get(new_obj, "glossary");
  printf("new_obj.to_string()=%s\n", json_object_to_json_string(new_obj));
  new_obj = json_object_object_get(new_obj, "pageCount");
  int pageCount = json_object_get_int(new_obj);
  printf("Page count = %d", pageCount);
  json_object_put(new_obj);
  return 0;
}

Makefile:

all: static
# if you didn't do `sudo make install` you'll need to add your own paths
# to json.json.h and libjson.so - something like -I/usr/local/include/ -L/usr/local/lib
static:
  gcc -static -o json-example-static json-example.c -ljson
  ./json-example-static
shared:
  gcc -o json-example-shared json-example.c -L/usr/local/lib -ljson
  ./json-example-shared
.PHONY: all static shared

Make json-example

make static
make shared

Hopefully that's enough to get you started. The big thing is that when you compile your own projects, make sure that you include the json library and paths.

Segfaults

If you get a segfault it's most likely that you're accessing a key that doesn't exist.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值